I have an image (in .png format), and I want this picture to convert to binary.
How can this be done using C#?
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);
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.
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
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));
Since you have a file use:-
Response.ContentType = "image/png";
Response.WriteFile(physicalPathOfPngFile);
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.