在 C# 中将一个 byte[] 拆分为多个 byte[] 数组 [英] Splitting a byte[] into multiple byte[] arrays in C#

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

问题描述

我正在尝试分块"图像的字节.这将允许我分部分上传大图像.我将图像当前存储为一个大字节 [].我想将字节数组拆分为 byte[] ,最大长度为 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-of-byte)通常就足够了.如果你的上传 API 只接受 byte[],那么你仍然不应该把它完全分块;只需使用单个 512 缓冲区并使用 Buffer.BlockCopy 将其加载到连续的数据块中.您可能需要调整 (Array.Resize) final 块的大小,但最多需要 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 加载数据(如果数据来自文件,这将工作得很好);只需使用 Read(在循环中,处理返回值等)来填充最大 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);
    }
}

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

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