我正在构建一个信息块,最终将其转换为字节数组。我想知道是否可以将其转换为图像?
我知道它最终不会“显示任何东西”有意义,这将是一个更抽象的结果,而这正是我正在寻找的。
我已经尝试过以下代码,但它返回异常...:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
您当前正在尝试解析随机字节数组,就好像它包含完整的有效图像文件一样,包括某些图像格式的有效标头。您的字节数组很可能不包含此类标头,因此无法将其解析为图像。尝试这样的事情:
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;
}
Run Code Online (Sandbox Code Playgroud)