简体   繁体   English

字节数组到图像C#

[英]Byte array to Image C#

I have a simple byte string (elements of a matrix read row by row) . 我有一个简单的字节串(矩阵的元素逐行读取)。 I wish to plot it in a image in c#. 我希望将其绘制在c#中的图像中。 Is there any simple way to do this. 有没有简单的方法可以做到这一点。

On the internet I found byte array to image conversion , but I assume that for this the byte string should have a certain format because I did not see any establishing of the width and height. 在互联网上,我发现了字节数组到图像的转换,但是我认为对此字节字符串应该具有某种格式,因为我没有看到宽度和高度的任何确定。

Any suggestions? 有什么建议么?

Assuming your bytes string contains color data for each pixel of an image in a one of the supported pixel formats , you can create a Bitmap with a specific size using this constructor: Bitmap(int width, int height . 假设你的字节字符串包含颜色数据上,以在支持的一个图像的每个像素的像素格式 ,您可以创建一个Bitmap使用此构造特定大小: Bitmap(int width, int height

Then lock the bitmap into system memory using Bitmap.LockBits(Rectangle, ImageLockMode, PixelFormat) and get the address of the first pixel data in the bitmap using BitmapData.Scan0 . 然后使用Bitmap.LockBits(Rectangle, ImageLockMode, PixelFormat)将位图锁定到系统内存中Bitmap.LockBits(Rectangle, ImageLockMode, PixelFormat)并使用BitmapData.Scan0获得位图中第一个像素数据的地址。

After that, you can manipulate the raw bitmap data. 之后,您可以操作原始位图数据。 For example, you can copy your bytes into it using, for example, Marshal.Copy(Byte[], Int32, IntPtr, Int32) . 例如,您可以使用Marshal.Copy(Byte[], Int32, IntPtr, Int32)将字节复制到其中。

And finally unlock the bitmap with Bitmap.UnlockBits(BitmapData) . 最后使用Bitmap.UnlockBits(BitmapData)解锁位图。

Voila! 瞧! You have created a bitmap from a byte array. 您已经从字节数组创建了位图。

Have you tried this code: 您是否尝试过以下代码:

public Bitmap ConvertBytesToImage(byte[] BytesToConvert)
{
    MemoryStream ms = new MemoryStream(BytesToConvert);
    try { return new Bitmap(ms); }
    catch { return null; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM