C# 将图像转换为二进制?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1373032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert image to binary?
提问by Martijn
I have an image (in .png format), and I want this picture to convert to binary.
我有一张图片(.png 格式),我希望这张图片转换为二进制文件。
How can this be done using C#?
如何使用 C# 做到这一点?
采纳答案by AnthonyWJones
Since you have a file use:-
由于您有文件使用:-
Response.ContentType = "image/png";
Response.WriteFile(physicalPathOfPngFile);
回答by Svetlozar Angelov
byte[] b = File.ReadAllBytes(file);
Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
打开一个二进制文件,将文件内容读入一个字节数组,然后关闭文件。
回答by Andrew Hare
Try this:
尝试这个:
Byte[] result
= (Byte[])new ImageConverter().ConvertTo(yourImage, typeof(Byte[]));
回答by Alistair Evans
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.
然后数据将包含图像的内容。
回答by Raúl Roa
First, convert the image into a byte array using ImageConverterclass. Then specify the mime typeof your png image, and voila!
首先,使用ImageConverter类将图像转换为字节数组。然后指定png 图像的mime 类型,瞧!
Here's an example:
下面是一个例子:
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Byte[]));
Response.ContentType = "image/png";
Response.BinaryWrite((Byte[])tc.ConvertTo(img,tc));
回答by omid.n
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);
回答by omid.n
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
只需使用上面的代码,我认为您的问题将得到解决
回答by Gayan Chinthaka Dharmarathna
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));