在C#中将图像输入到字节[]的正确方法是什么?

时间:2013-06-26 22:44:03

标签: c# image

我正在尝试使用从剪贴板粘贴的图像,如截图。

以下是一段代码:

public void PasteImage(Image pasteImage)
{
    MemoryStream image = new MemoryStream();
    pasteImage.Save(image, pasteImage.RawFormat);
    image.Position=0;
    byte[] byteImage = image.ToArray();

在线:

pasteImage.Save(image, pasteImage.RawFormat);

我收到此错误:

  

发生了类型为“System.ArgumentNullException”的未处理异常   在System.Drawing.dll

中      

附加信息:值不能为空。

我正在关注我在此主题上发现的以前的stackoverflow帖子,例如How to compare two images using byte arraysHow to convert image in byte array,并且无法让它发挥作用。

我想知道从剪贴板中检索到的图像是否有特定的内容。我正在使用此代码来获取图像:

    if (Clipboard.ContainsImage())
    {
        Image pasteImage = GetClipboardImage();
        PasteImage(pasteImage);
    }

修改

这是GetClipboardImage()背后的代码:

public Image GetClipboardImage()
        {
            System.Drawing.Image returnImage = null;
            if (Clipboard.ContainsImage())
            {
                returnImage = Clipboard.GetImage();
            }
            return returnImage;
        }

如果我在行上设置了一个断点,那么我可以看到pasteImage和pastImage.RawFormat都不是null:

enter image description here

enter image description here

这看起来很相似,作为一个例子,我对此有所了解并报告回来:How can I get an image out of the clipboard without losing the alpha channel in .NET?

1 个答案:

答案 0 :(得分:0)

查看MSDN article for Save Image,您可能需要尝试:

而不是

pasteImage.Save(image, pasteImage.RawFormat);

pasteImage.Save(image, System.Drawing.Imaging.ImageFormat.RawFormat)