c# convert image to byte array

i was loooking for a faster solution to convert image to byte array using the 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 i searched and found this 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 is my call:

` private void Form1_Load(object sender, EventArgs e) { Bitmap curr = GetDesktopImage(); byte[] buff = BitmapToByteArray(curr); }

than i got an expcetion arithmetic operation resulted in an overflow and i discoverd that numbofbytes was negative so it couldn't make the array so i used Math.Abs() but than i got another error on that line Marshal.Copy(ptr, bytedata, 0, numbytes); and the error : Attempted to read or write protected memory. This is often an indication that other memory is corrupt. why is it happening? GetDesktopImage() is a method i have that uses the gdi to take screenshots according to this and the method is actully (i tried to display on picturebox) but im facing weird errors when trying to convert to bytes..

this is 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; }

-------------Problems Reply------------

For the negative stride, the MSDN doc says:

The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary. If the stride is positive, the bitmap is top-down. If the stride is negative, the bitmap is bottom-up.

Your bitmap is bottom-up. Have a look at this nice explanation here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa473780(v=vs.85).aspx

To copy the bytes, you need to calculate the starting address like in this answer: http://stackoverflow.com/a/17116072/200443.

If you want to reverse the bytes order, you need to copy one line at a time.

Category:c# Views:31 Time:2019-03-20

Related post

  • How to convert image to byte array using javascript only to store image on sql server? 2012-02-13

    I am struggling converting image to byte array using client side script. I have to convert image to byte array, and pass this array to web service , so that the web services can save the image in sql server. Any one please help me. --------------Solu

  • how to convert image to byte array in java? 2010-07-09

    I want to convert an image to byte array and vice versa. Here, the user will enter the name of the image (.jpg) and program will read it from the file and will convert it to a byte array. --------------Solutions------------- BufferedImage consists of

  • How to convert image in byte array 2010-09-27

    Can anybody suggest how can I can convert an image into a byte array..and vice versa. If anybody has some code samples help me out. I'm developing a WPF application and enable to find stream reader. --------------Solutions------------- Code public by

  • How to convert image to byte array and convert back byte array to image 2012-03-22

    I am trying to convert an image to byte array and converting back byte array to image in Android Emulator. First part is working fine but the second part is not creating the image file in Android emulator. Please suggest me if there is any correction

  • Converting image to byte array? 2010-10-25

    What is the need/purpose of converting an image to a byte array? Why do we need to do this? --------------Solutions------------- What's the purpose of converting an Image to a byte array? Saving an image to disk Serializing the image to send to a web

  • Fastest way to convert Image to Byte array 2013-06-27

    I am making Remote Desktop sharing application in which I capture an image of the Desktop and Compress it and Send it to the receiver. To compress the image I need to convert it to a byte[]. Currently I am using this: public byte[] imageToByteArray(S

  • Problem with converting image to byte array 2011-03-24

    For school we have to do a project in stenography, I have chosen to use a bmp and put text into it. It works fine with normal pictures but from the moment on when you have pictures with a same byte sequence for example a white area or the image where

  • Convert image to byte array on Windows Phone 7 No System.Drawing Dll any other way? 2012-04-30

    Byte[] result = (Byte[])new ImageConverter().ConvertTo(img1, typeof(Byte[])); //I cant use Image Converter add Image Class ? Drawing dll MemoryStream ms = new MemoryStream(); img1.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray();

  • Image to Byte array in J2ME 2010-08-09

    How to convert image to byte array in J2ME ?? --------------Solutions------------- You can't get the original (probably compressed) image back. But you can use [Image.getRGB()][1] to retrieve the RGB data; this can then be stored somewhere, and the i

  • How can I convert an HTML page to an image or PDF and then convert it to byte array? 2010-12-09

    How can I convert an HTML page to an image or PDF and then convert it to byte array? --------------Solutions------------- I've used PrinceXML as a tool to convert from html to PDF before, it worked excellently. It depends. In the way of pdf, do you j

  • How Can I Convert My new Byte Array To an Image 2014-03-05

    i have write this code for extracting bitplane1 of my image . but i have exceptions. actually i get an image and convert it to a byte array so after i change this byte array i want to convert this new byte array to image ? could you please give me so

  • How to convert UIImage to byte array or base64encoding? 2011-08-25

    I have an image which i want to send as byte array to a server .I want to know how to convert uiimage to byte array ? I have to send parameter as <byteArrayIn>base64Binary</byteArrayIn> to the web service Thanks in advance --------------S

  • Cannot convert CString to BYTE array 2010-03-17

    I need to convert CString to BYTE array. I don't know why, but everything that I found in internet does not work :( For example, I have CString str = _T("string"); I've been trying so 1) BYTE *pbBuffer = (BYTE*)(LPCTSTR)str; 2) BYTE *pbBuffer = new B

  • java: can I convert strings to byte arrays, without a BOM? 2010-03-28

    Suppose I have this code: String encoding = "UTF-16"; String text = "[Hello StackOverflow]"; byte[] message= text.getBytes(encoding); If I display the byte array in message, the result is: 0000 FE FF 00 5B 00 48 00 65 00 6C 00 6C 00 6F 00 20 ...[.H.e

  • Convert into to byte array and insert into other array 2010-10-20

    I work in a c# wpf application in which I want to do several things. I'm working with byte arrays to compose MIDI Show Control messages (specified in the MSC Specification 1.0). The structure of this message is that a 0x00 byte is like a comma betwee

  • Convert long to byte array and add it to another array 2010-11-28

    I want to change a values in byte array to put a long timestamp value in in the MSBs. Can someone tell me whats the best way to do it. I do not want to insert values bit-by-bit which I believe is very inefficient. long time = System.currentTimeMillis

  • different results when converting int to byte array - .NET vs Java 2011-05-06

    I am trying to send data from a java client to a c# server and having trouble converting int to byte array. when i am converting the number 8342 with c# using this code: BitConverter.GetBytes(8342) the result is: x[4] = { 150, 32, 0, 0 } with java i

  • is it possibble to load image in byte array in javascript 2011-05-12

    is it possible to load an image in byte array in javascript instead of loading it to canvas?? i want to make an image editor in javascript webOS but i cant use toDataURl method of HTML 5 canvas because webOs dont support it .... --------------Solutio

  • Java - Convert int to Byte Array of 4 Bytes? 2011-06-16

    Possible Duplicate: Convert integer into byte array (Java) I need to store the length of a buffer, in a byte array 4 bytes large. Pseudo code: private byte[] convertLengthToByte(byte[] myBuffer) { int length = myBuffer.length; byte[] byteLength = new

  • What occurs when a string is converted to a byte array 2011-08-21

    I think that this is a newbie type question but I have quite understood this. I can find many posts on how to convert a string to a byte array in various languages. What I do not understand is what is happening at a character by character basis. I un

  • More effective way to convert file to byte array to string and back 2011-10-19

    I have following way of converting file to byte array and than to string and back. InputStream is = new FileInputStream(new File("c:/original.png")); String temp = Hex.encodeHexString(IOUtils.toByteArray(is)); System.out.println(temp); byte[] b = Hex

  • Convert object to byte array and viceversa without serialization 2011-10-23

    I have a java project in which I have to save the data of each run for later use. The professor wants us to use a RandomAccessFile to do this so I have to convert the objects to bytes so they can be stored in the RAF. The major problem is that if we

  • Android how to resize image in byte array format 2011-10-28

    I have a camera activity. My activity will take a picture and then I have an AsyncTask to save the pic to the device. Here is my code: class SavePhotoTask extends AsyncTask<byte[], String, String> { private ProgressDialog dialog; // protected C

  • GWT - get image from byte array 2012-02-13

    I tried this code to decode base64 image to binary; the thing I want to get image of the byte array on client... I am not pretty sure how to create image of byte array on gwt client so I need your help Any useful comment is appreciated --------------

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.087 (s). 11 q(s)