我有一个图像(.png格式),我希望这张图片转换为二进制。
如何使用C#完成此操作?
答案 0 :(得分:21)
答案 1 :(得分:11)
试试这个:
Byte[] result
= (Byte[])new ImageConverter().ConvertTo(yourImage, typeof(Byte[]));
答案 2 :(得分:6)
由于您有使用文件: -
Response.ContentType = "image/png";
Response.WriteFile(physicalPathOfPngFile);
答案 3 :(得分:3)
你可以这样做:
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
BinaryReader streamreader = new BinaryReader(stream);
byte[] data = streamreader.ReadBytes(stream.Length);
然后数据将包含图像的内容。
答案 4 :(得分:0)
首先,使用ImageConverter类将图像转换为字节数组。然后指定你的png图像的mime type,瞧!
以下是一个例子:
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Byte[]));
Response.ContentType = "image/png";
Response.BinaryWrite((Byte[])tc.ConvertTo(img,tc));
答案 5 :(得分:0)
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);
答案 6 :(得分:0)
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;
}
只需使用上面的代码,我认为您的问题将得到解决
答案 7 :(得分:0)
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));