拆分一个byte []成多个字节[]在C#中的数组 [英] Splitting a byte[] into multiple byte[] arrays in C#

查看:1198
本文介绍了拆分一个byte []成多个字节[]在C#中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为块上的图像的字节数。这将让我在部分上传一个大的图像。我曾图像当前存储为一个大的byte []。我想字节数组字节拆分[] S'与512元的最大长度。但是,我不知道如何以最有效的方式做到这一点。

I am trying to "chunk" up the bytes of an image. This will allow me to upload a large image in portions. I have the image currently stored as one large byte[]. I would like to split the byte array into byte[]'s with a maxlength of 512 elements. However, I'm not sure how to do this in the most efficient way.

有谁知道我怎么能以最有效的方式做到这一点?

Does anyone know how I can do this in the most efficient manner?

推荐答案

最有效的方法是:不。如果你已经有了图像作为一个字节[]那么对于本地代码,只需指定偏移量和长度(也许索姆ArraySegment-的字节)通常是足够的。如果您上传API只需要的byte [],那么你还是不应该完全大块它;只需使用一个单一的512缓冲,并使用Buffer.BlockCopy加载它会将数据的连续件。你可能需要调整(Array.Resize)中的最后的块,但应根据需要最多2个数组

The most efficient method would be: not to. If you already have the image as a single byte[] then for local code, just specifying the offset and length (perhaps som ArraySegment-of-byte) is usually sufficient. If your upload API only takes byte[], then you still shouldn't chunk it completely; just use a single 512 buffer and use Buffer.BlockCopy to load it will successive pieces of the data. You may need to resize (Array.Resize) the final chunk, but at most 2 arrays should be needed.

甚至更好;避免需要一个byte []首先:考虑通过流API加载数据(这将工作做好,如果数据是从一个文件来);只需使用读取(在一个循环,处理返回值等)来填充512最大大块例如(未经测试,只是说明):

Even better; avoid needing a byte[] in the first place: consider loading the data via a streaming API (this will work well if the data is coming from a file); just use Read (in a loop, processing the returned value etc) to populate chunks of max 512. For example (untested, just of illustration):

byte[] buffer = new byte[512];
while(true) {
    int space = 512, read, offset = 0;
    while(space > 0 && (read = stream.Read(buffer, offset, space)) > 0) {
        space -= read;
        offset += read;
    }
    // either a full buffer, or EOF
    if(space != 0) { // EOF - final
       if(offset != 0) { // something to send
         Array.Resize(red buffer, offset);
         Upload(buffer);
       }
       break;
    } else { // full buffer
       Upload(buffer);
    }
}

这篇关于拆分一个byte []成多个字节[]在C#中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆