将图片从图片框保存为png C#

Saving an image from picture box to png C#

美好的一天! 我正在尝试从 PictureBox 保存图像,但是它给我一个错误。

        pictureBox1.ImageLocation = @"C:\emo\hairs\Hair-01.png";
        this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        pictureBox1.Image.Save(@"C:\Coke\res1.png", System.Drawing.Imaging.ImageFormat.Png);

这是错误:

An unhandled exception of type 'System.NullReferenceException' occurred in Emo.exe Additional information: Object reference not set to an instance of an object.

请帮我确定我的答案。

您收到 NullReferenceException 异常,因为图片框的 Image 属性 为空。

尝试 PictureBox Load 方法,例如:

pictureBox1.ImageLocation = @"C:\emo\hairs\Hair-01.png";
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
pictureBox1.Load();
pictureBox1.Image.Save(@"C:\Coke\res1.png", System.Drawing.Imaging.ImageFormat.Png);

另一种选择是使用另一种overload of the Load()方法:

pictureBox1.Load(@"C:\emo\hairs\Hair-01.png");
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
pictureBox1.Image.Save(@"C:\Coke\res1.png", System.Drawing.Imaging.ImageFormat.Png);