我正在构建一个信息 block ,最终将其转换为字节数组。 我想知道是否可以将其转换为图像?
我知道它最终不会“显示任何内容”,而是一个更抽象的结果,而这正是我想要的。
我尝试了以下代码,但它返回异常...:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
我该怎么做?
最佳答案
您当前正在尝试解析随机字节数组,就好像它包含完整的有效图像文件,包括某些图像格式的有效 header 。您的字节数组很可能不包含此类 header ,因此无法将其解析为图像。尝试这样的事情:
public Image byteArrayToImage(byte[] byteArrayIn)
{
int size = (int)Math.Sqrt(byteArrayIn.Length); // Some bytes will not be used as we round down here
Bitmap bitmap = new Bitmap(size, size, PixelFormat.Format8bppIndexed);
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);
try
{
// Copy byteArrayIn to bitmapData row by row (to account for the case
// where bitmapData.Stride != bitmap.Width)
for (int rowIndex = 0; rowIndex < bitmapData.Height; ++rowIndex)
Marshal.Copy(byteArrayIn, rowIndex * bitmap.Width, bitmapData.Scan0 + rowIndex * bitmapData.Stride, bitmap.Width);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
return bitmap;
}
关于c# - 从 "random"字节数组生成(并保存在磁盘中)图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24140227/