将图像转换为字节[] [英] Convert Image into Byte[]
问题描述
我想开始学习如何将图像拆开以找到图像中的图案,但是要做到这一点,我需要首先了解它的构成.我想将png转换为字节数组,以便将其打印出来,看看是否可以识别数组值中的简单模式.
I want to start learning about how to tear images apart to find patterns in them but in order to do that I need to first see what makes it up. I want to take a png and convert it into a byte array so I can print it out and see if I can recognize simple patterns in the array values.
到目前为止,我有这个
public MainWindow()
{
InitializeComponent();
System.Drawing.Image image;
image = System.Drawing.Image.FromFile("one.png");
byte[] imArray = imageToByteArray(image);
String bytes = "";
foreach (Char bite in imArray)
{
bytes += "-"+bite;
}
MessageBox.Show(bytes);
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
但是它似乎没有用.调用转换方法时,它给我一个空错误.我不知道为什么这行不通,因为我对这些组件的了解很少.
But it doesn't seem to be working. It gives me a null error when the conversion method is called. I have NO clue why this isn't working because my understanding of the compenents is nill.
如果您可以提出一种更简便的方法来随意发布此转化信息.我并没有停留在这段代码上,我只想要一个有效的示例,所以我有一个起点.
If you can suggest an easier way to make this conversion feel free to post it. Im not stuck on this code I just want a working example so I have a starting point.
谢谢!
推荐答案
我建议从Bitmap开始查看二进制数据-大多数其他格式都存储压缩后的数据,因此您没有机会通过看字节.
I'd recommend starting with Bitmap to look at binary data - most other formats store data compressed, so you have no chance to understand what is inside an image by looking at the bytes.
您想要的方法是 Bitmap.LockBits .本文还包括完整的示例,如何从文件读取并查看t位,摘录如下:
The method you want is Bitmap.LockBits. The article also includes complete sample how to read from file and look t bits, excerpt below:
Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData =
bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
Marshal.Copy(bmpData.Scan0, rgbValues, 0, bytes);
这篇关于将图像转换为字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!