Reputation: 24789
I have an image (in .png format), and I want this picture to convert to binary.
How can this be done using C#?
Upvotes: 11
Views: 103884
Reputation: 411
using System.IO;
FileStream fs=new FileStream(Path, FileMode.Open, FileAccess.Read); //Path is image location
Byte[] bindata= new byte[Convert.ToInt32(fs.Length)];
fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
Upvotes: 0
Reputation: 491
System.Drawing.Image image = System.Drawing.Image.FromFile("filename");
byte[] buffer;
MemoryStream stream = new MemoryStream();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
buffer = stream.ToArray(); // converted to byte array
stream = new MemoryStream();
stream.Read(buffer, 0, buffer.Length);
stream.Seek(0, SeekOrigin.Begin);
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
Upvotes: 0
Reputation:
public static byte[] ImageToBinary(string imagePath)
{
FileStream fS = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
return b;
}
just use above code i think your problem will be solved
Upvotes: 0
Reputation: 12386
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));
Upvotes: 0
Reputation: 36473
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.
Upvotes: 3
Reputation: 189437
Since you have a file use:-
Response.ContentType = "image/png";
Response.WriteFile(physicalPathOfPngFile);
Upvotes: 6
Reputation: 351466
Try this:
Byte[] result
= (Byte[])new ImageConverter().ConvertTo(yourImage, typeof(Byte[]));
Upvotes: 11
Reputation: 21660
byte[] b = File.ReadAllBytes(file);
Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
Upvotes: 26