[英]conversion of image to byte array
谁能告诉我图像(.jpg,.gif,.bmp)如何转换为字节数组?
The easiest way to convert an image to bytes is to use the ImageConverter class under the System.Drawing namespace 将图像转换为字节的最简单方法是使用System.Drawing命名空间下的ImageConverter类
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
If your image is already in the form of a System.Drawing.Image
, then you can do something like this: 如果您的图像已经采用
System.Drawing.Image
的形式,则可以执行以下操作:
public byte[] convertImageToByteArray(System.Drawing.Image image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
// or whatever output format you like
return ms.ToArray();
}
}
You would use this function with the image in your picture box control like this: 您可以对图片框控件中的图像使用此功能,如下所示:
byte[] imageBytes = convertImageToByteArray(pictureBox1.Image);
I've assumed what you want is the pixel values. 我假设您想要的是像素值。 Assuming
bitmap
is a System.Windows.Media.Imaging.BitmapSource
: 假设
bitmap
是System.Windows.Media.Imaging.BitmapSource
:
int stride = bitmap.PixelWidth * ((bitmap.Format.BitsPerPixel + 7) / 8);
byte[] bmpPixels = new byte[bitmap.PixelHeight * stride];
bitmap.CopyPixels(bmpPixels, stride, 0);
Note that the 'stride' is the number of bytes required for each row of pixel ddata. 注意,“跨度”是像素ddata的每一行所需的字节数。 Some more explanation available here .
这里还有更多解释。
Based off of MusiGenesis; 基于MusiGenesis; helped me a lot but I had many image types.
帮助了我很多,但是我有很多图像类型。 This will save any image type that it can read.
这将保存它可以读取的任何图像类型。
System.Drawing.Imaging.ImageFormat ImageFormat = imageToConvert.RawFormat;
byte[] Ret;
try
{
using (MemoryStream ms = new MemoryStream())
{
imageToConvert.Save(ms, ImageFormat);
Ret = ms.ToArray();
}
}
catch (Exception) { throw; }
return Ret;
要从任何文件中获取字节,请尝试:
byte[] bytes = File.ReadAllBytes(pathToFile);
You can use File.ReadAllBytes method to get bytes 您可以使用File.ReadAllBytes方法获取字节
If you are using FileUpload class then you can use FileBytes Property to get the Bytes as Byte Array. 如果使用的是FileUpload类,则可以使用FileBytes属性获取Bytes作为字节数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.