c#如何将pictureBox.Image转换为字节数组?

时间:2015-02-10 08:00:40

标签: c# picturebox

我在图像中寻找快速方式Picturebox转换为字节数组。

我看到了这段代码,但我并不需要它。因为图片的图片框是从数据库中读取的数据。 所以我不知道ImageFormat

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

所以如果有人知道的话,请告诉我

谢谢!玩得开心!

2 个答案:

答案 0 :(得分:3)

尝试阅读:http://www.vcskicks.com/image-to-byte.php 希望它会帮助你。

编辑:我猜你有来自Fung链接的链接的代码片段。如果是这样,那么你的问题就在于答案,你只需要向下滚动......

2nd Edit(来自页面的代码片段 - 感谢Fedor的信息):

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

答案 1 :(得分:2)

这可能不是您正在寻找的,但如果您正在寻找执行某些像素操作的性能,可能对您有用..我认为这样做是值得的在这里提到它。

由于您已经使用Image imageIn加载了图像,因此您可以直接访问图像缓冲区而无需执行任何复制,从而节省时间和资源:

public void DoStuffWithImage(System.Drawing.Image imageIn)
{
    // Lock the bitmap's bits.  
    Rectangle rect = new Rectangle(0, 0, imageIn.Width, imageIn.Height);
    System.Drawing.Imaging.BitmapData bmpData =
                    imageIn.LockBits(rect, System.Drawing.Imaging.ImageLockMode.Read,
                    imageIn.PixelFormat);

    // Access your data from here this scan0,
    // and do any pixel operation with this imagePtr.
    IntPtr imagePtr = bmpData.Scan0;

    // When you're done with it, unlock the bits.
    imageIn.UnlockBits(bmpData);
}

有关更多信息,请查看此MSDN页面

ps:这个bmpData.Scan0当然只允许你访问像素有效载荷。又名,没有标题!

相关问题