0

我正在尝试将新产品插入product表中,其中一列是图像。这是我的代码:

 private void pictureBox1_Click(object sender, EventArgs e)
 {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            pictureBox1.Image = Image.FromFile(dlg.FileName);
            ImageToByte(pictureBox1.Image);
        }

        dlg.Dispose();
    }

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

我收到此错误:

无法将参数值从位图转换为字节[]。

我该如何解决?

谢谢

4

2 回答 2

0

您可以通过以下方式执行此操作:

public static byte[] ToByteArray(this Image image, ImageFormat format)
{
    using(MemoryStream ms = new MemoryStream())
    {
        image.Save(ms, format);
        return ms.ToArray();
    }
}

并使用这个:

var image = yourImageFromPictureBox;
byte[] arr = image.ToByteArray(ImageFormat.Bmp);
于 2013-08-03T20:53:37.720 回答
0

将图像保存到内存流,然后转换为 byte 数组:

private byte[] ImageToByte(System.Drawing.Image imageToConvert,
                                                   System.Drawing.Imaging.ImageFormat formatOfImage)
            {
                byte[] Ret;
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        imageToConvert.Save(ms, formatOfImage);
                        Ret = ms.ToArray();
                    }
                }
                catch (Exception) { throw; }
                return Ret;
            }

在您的情况下位图的示例用法

ImageToByte( [your image here], System.Drawing.Imaging.ImageFormat.Bmp);
于 2013-08-03T20:52:32.950 回答