值不能为空。参数名:编码器。

5

我需要截取屏幕的一部分并检查截图是否与 pictureBox2 中的图像相等,这是不起作用的代码:

这是无法运行的代码行:

pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);

错误信息如下:

值不能为 null。
参数名: encoder

以下是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Bitmap screenshot = new Bitmap(SystemInformation.VirtualScreen.Width,
            SystemInformation.VirtualScreen.Height,
            PixelFormat.Format32bppArgb);
        public Form1()
        {
            InitializeComponent();

        }



        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Bitmap screenshot = new Bitmap(SystemInformation.VirtualScreen.Width,
                SystemInformation.VirtualScreen.Height,
                PixelFormat.Format32bppArgb);
            Graphics screenGraph = Graphics.FromImage(screenshot);
            screenGraph.CopyFromScreen(
                SystemInformation.VirtualScreen.X + 1080,
                SystemInformation.VirtualScreen.Y + 100,
                0,
                0,
                new Size(190, 480),//SystemInformation.VirtualScreen.Size,
                CopyPixelOperation.SourceCopy);
            pictureBox1.Image = screenshot;
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
            String image_one = Convert.ToBase64String(ms.ToArray());
            ms.Position = 0;
            pictureBox2.Image.Save(ms, pictureBox2.Image.RawFormat);
            String image_three = Convert.ToBase64String(ms.ToArray());
            ms.Position = 0;
            ms.Close();
            if (image_one.Equals(image_three))
                textBox1.Text = "SAME";
            else
                textBox1.Text = "DIFFERENT";
        }

    }
}

我能做什么?


pictureBox1.Image <- 检查它是否不为NULL - MajkeloDev
@MajkeloDev 这将导致 NRE 而不是 ArgumentNullException。 - MakePeaceGreatAgain
1
通过代码调试并查看哪些内容为空,这应该不是问题。此外,您可能希望将MemoryStream封装在using语句中:using(MemoryStream ms = new MemoryStream()) { } 在结束括号处,MemoryStream将自动被处理。 - Paul Weiland
@Maiky Ganon - 将此行放入 Try Catch 块中并显示堆栈跟踪。 - MajkeloDev
@HimBromBeere 你说得对。 - MajkeloDev
1个回答

17

您的图像存在于内存中,因此没有设置RawFormat编码器。请指定一个格式,如System.Drawing.Imaging.ImageFormat.Png或其他。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接