views:

3429

answers:

5

I have an image (.png) and I want this picture to convert to binary. How can I do this?

I am using Webforms ASP.NET C#

+3  A: 
byte[] b = File.ReadAllBytes(file);

File.ReadAllBytes Method

Opens a binary file, reads the contents of the file into a byte array, and then closes the file.

Svetlozar Angelov
Unless there is some need to process that array before sending it to the response you may as well let ASP.NET handle it using WriteFile
AnthonyWJones
+1  A: 

Try this:

Byte[] result 
    = (Byte[])new ImageConverter().ConvertTo(yourImage, typeof(Byte[]));
Andrew Hare
+2  A: 

Since you have a file use:-

 Response.ContentType = "image/png";
 Response.WriteFile(physicalPathOfPngFile);
AnthonyWJones
+1  A: 

You could do:

    MemoryStream stream = new MemoryStream();
    image.Save(stream, ImageFormat.Png);
    BinaryReader streamreader = new BinaryReader(stream);

    byte[] data = streamreader.ReadBytes(stream.Length);

data would then contain the contents of the image.

Kazar
What datatype does image have? I am using Webforms...
Martijn
System.Drawing.Image
Kazar
A: 

First, convert the image into a byte array using ImageConverter class. Then specify the mime type of your png image, and voila!

Here's an example:

TypeConverter tc = TypeDescriptor.GetConverter(typeof(Byte[]));
Response.ContentType = "image/png";
Response.BinaryWrite((Byte[])tc.ConvertTo(img,tc));
Raúl Roa