c# convert image to byte array -
i loooking faster solution convert image byte array using regular method:
public byte[] imagetobytearray(system.drawing.image imagein) { memorystream ms = new memorystream(); imagein.save(ms,system.drawing.imaging.imageformat.gif); return ms.toarray(); }
so searched , found one
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; }
this call:
` private void form1_load(object sender, eventargs e) { bitmap curr = getdesktopimage(); byte[] buff = bitmaptobytearray(curr); }
than got expcetion arithmetic operation resulted in overflow
, discoverd numbofbytes
negative couldn't make array used math.abs()
got error on line marshal.copy(ptr, bytedata, 0, numbytes);
, error : attempted read or write protected memory. indication other memory corrupt. why happening? getdesktopimage()
method have uses gdi take screenshots according this , method actully (i tried display on picturebox) im facing weird errors when trying convert bytes..
this getdesktopimage()
public static bitmap getdesktopimage() { //in size variable shall keep size of screen. size size; //variable keep handle 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; }
for negative stride, msdn doc says:
the stride width of single row of pixels (a scan line), rounded four-byte boundary. if stride positive, bitmap top-down. if stride negative, bitmap bottom-up.
your bitmap bottom-up. have @ nice explanation here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa473780(v=vs.85).aspx
to copy bytes, need calculate starting address in answer: https://stackoverflow.com/a/17116072/200443.
if want reverse bytes order, need copy 1 line @ time.
Comments
Post a Comment