Bitmap to byte array?
-
Hi, I have a System.Drawing.Bitmap of a screen capture that I want to convert to a byte array. Any ideas on how to do this? I expected the bitmap object to have some sort of ToArray method, but it hasn't. I'm rather stumped. TIA Dr Herbie Remember, half the people out there have below average IQs.
-
Hi, I have a System.Drawing.Bitmap of a screen capture that I want to convert to a byte array. Any ideas on how to do this? I expected the bitmap object to have some sort of ToArray method, but it hasn't. I'm rather stumped. TIA Dr Herbie Remember, half the people out there have below average IQs.
You can save the image to a
System.IO.MemoryStream
, which does have the elusiveToArray
method. Charlie if(!curlies){ return; } -
Hi, I have a System.Drawing.Bitmap of a screen capture that I want to convert to a byte array. Any ideas on how to do this? I expected the bitmap object to have some sort of ToArray method, but it hasn't. I'm rather stumped. TIA Dr Herbie Remember, half the people out there have below average IQs.
-
This should do the trick :) public static byte[] GenerateImageBytes(Bitmap bm) { byte[] bytes = null; System.IO.MemoryStream ms = new System.IO.MemoryStream(); bm.Save(ms, ImageFormat.Gif); bytes = ms.ToArray(); ms.Close(); return bytes; } Thomas
Or, with slightly more pleasant syntax, with better resource management:
public static byte[] GenerateImageBytes(Bitmap bm)
{
using(MemoryStream ms = new MemoryStream())
{
bm.Save(ms, ImageFormat.Gif);
return ms.ToArray();
}
}Tech, life, family, faith: Give me a visit. I'm currently blogging about: Cops & Robbers Judah Himango
-
Or, with slightly more pleasant syntax, with better resource management:
public static byte[] GenerateImageBytes(Bitmap bm)
{
using(MemoryStream ms = new MemoryStream())
{
bm.Save(ms, ImageFormat.Gif);
return ms.ToArray();
}
}Tech, life, family, faith: Give me a visit. I'm currently blogging about: Cops & Robbers Judah Himango
-
That's what the using statement is for. The using clause automatically disposes of any IDisposable objects, including MemoryStream, thus it will call the appropriate close method when the scope leaves the using clause.
Tech, life, family, faith: Give me a visit. I'm currently blogging about: Cops & Robbers Judah Himango