c# - 写入字节数组的大小(C# winforms)
问题描述
我正在将一些内容写入二进制文件。一项是图像,因此将图像转换为字节数组并将其写入如下。
BinaryWriter bw = (BinaryWriter)writer;
WritePropertyTag(property); //IMAGE_TAG
bw.Write((short)(sizeofshort + imagedata.Length + (writesize ? sizeofshort : 0)));
if (writesize)
{
bw.Write((short)(imagedata.Length));
}
bw.Write(imagedata);
并用下面的代码读回它:
short datasize = binReaderIn.ReadInt16();
byte[] data = new byte[datasize];
binReaderIn.Read(data, 0, datasize);
Image img = (Bitmap)((new ImageConverter()).ConvertFrom(data));
如果字节数组相对较小(短数字),上述方法非常有效。
当我们想要存储更大的图像(大约字节数组大小为 25k)时,它会失败。我尝试在上面的代码块中使用 long 而不是 short 并使用 ReadInt64() 方法读取,但没有得到正确的大小。请帮忙。谢谢。
解决方案
BinaryWriter bw = (BinaryWriter)writer;
WritePropertyTag(property);
bw.Write((uint)(sizeofshort + data.Length + (writesize ? sizeofshort : 0)));
if (writesize)
{
bw.Write((uint)(data.Length));
}
bw.Write(data);
使用 uint 而不是 short 解决了这个问题。
推荐阅读
- javascript - 在 JavaScript 中处理从 ajax 获取请求的文件下载
- angular-cli - 无法生成库。无效的规则结果:Promise 类的实例
- c# - .Net Core 如何使用 DI 服务新建一个类?
- c# - Newtonsoft 中的 com.google.gson.JsonArray
- haskell - 如何在仆人处理程序 monad 中处理异常?
- vue.js - 在 Nuxt 应用程序中关闭 webpack-hot-middleware 客户端覆盖
- ansible - 如何将 Ansible 任务运行到限制数量的项目?
- javascript - 无法根据子元素的高度设置元素的高度
- module - Orchard CMS 客户模块
- android - 我在 android studio 上的请求队列不起作用