[英]c# convert image to byte array
我一直在尋找一種使用常規方法將圖像轉換為字節數組的更快解決方案:
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
所以我搜索並找到了這個
public static byte[] BitmapToByteArray(Bitmap bitmap)
{
BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
int numbytes = bmpdata.Stride * bitmap.Height;
numbytes = Math.Abs(numbytes);
byte[] bytedata = new byte[numbytes];
IntPtr ptr = bmpdata.Scan0;
Marshal.Copy(ptr, bytedata, 0, numbytes);
bitmap.UnlockBits(bmpdata);
return bytedata;
}
這是我的電話:
` private void Form1_Load(object sender, EventArgs e)
{
Bitmap curr = GetDesktopImage();
byte[] buff = BitmapToByteArray(curr);
}
比我得到的期望arithmetic operation resulted in an overflow
,我發現numbofbytes
為負數,因此它無法制作數組,所以我使用Math.Abs()
但是我在那條線Marshal.Copy(ptr, bytedata, 0, numbytes);
上遇到另一個錯誤Marshal.Copy(ptr, bytedata, 0, numbytes);
錯誤:嘗試讀取或寫入受保護的內存。 這通常表明其他內存已損壞。 為什么會這樣呢? 我有一個GetDesktopImage()
方法,該方法使用gdi根據此方法截取屏幕截圖,並且該方法確實有效(我嘗試在圖片框上顯示),但是在嘗試轉換為字節時卻遇到了奇怪的錯誤。
這是GetDesktopImage()
public static Bitmap GetDesktopImage()
{
//In size variable we shall keep the size of the screen.
SIZE size;
//Variable to keep the handle to bitmap.
IntPtr hBitmap;
IntPtr hDC = PlatformInvokeUSER32.GetDC(PlatformInvokeUSER32.GetDesktopWindow());
IntPtr hMemDC = PlatformInvokeGDI32.CreateCompatibleDC(hDC);
size.cx = PlatformInvokeUSER32.GetSystemMetrics(PlatformInvokeUSER32.SM_CXSCREEN);
size.cy = PlatformInvokeUSER32.GetSystemMetrics(PlatformInvokeUSER32.SM_CYSCREEN);
hBitmap = PlatformInvokeGDI32.CreateCompatibleBitmap(hDC, size.cx, size.cy);
if (hBitmap != IntPtr.Zero)
{
IntPtr hOld = (IntPtr)PlatformInvokeGDI32.SelectObject(hMemDC, hBitmap);
PlatformInvokeGDI32.BitBlt(hMemDC, 0, 0, size.cx, size.cy, hDC, 0, 0, PlatformInvokeGDI32.SRCCOPY);
PlatformInvokeGDI32.SelectObject(hMemDC, hOld);
PlatformInvokeGDI32.DeleteDC(hMemDC);
PlatformInvokeUSER32.ReleaseDC(PlatformInvokeUSER32.GetDesktopWindow(), hDC);
Bitmap bmp = System.Drawing.Image.FromHbitmap(hBitmap);
PlatformInvokeGDI32.DeleteObject(hBitmap);
GC.Collect();
return bmp;
}
return null;
}
對於消極的進步, MSDN文檔說:
跨度是單行像素(掃描線)的寬度,四舍五入到四字節邊界。 如果跨度為正,則位圖是自頂向下的。 如果跨度為負,則位圖是自底向上的。
您的位圖是自下而上的。 在這里看看這個很好的解釋: https : //msdn.microsoft.com/zh-cn/library/windows/desktop/aa473780(v=vs.85).aspx
要復制字節,您需要像以下答案中那樣計算起始地址: https : //stackoverflow.com/a/17116072/200443 。
如果要反轉字節順序,則需要一次復制一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.