【问题标题】:Save an image in C#在 C# 中保存图像
【发布时间】:2014-09-13 21:50:05
【问题描述】:

我有应该保存图片(位图)的代码,但它没有保存它并且每次都抛出异常,这是什么问题?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;

namespace PicConv {
    public partial class Form1 : Form {
        Bitmap bmp;
        Bitmap bmp2;
        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {

            for (int y = 0; y < bmp.Height; y++) {
                for (int x = 0; x < bmp.Width; x++) {
                    Color c = bmp2.GetPixel(x, y);
                    byte r = c.R;
                    byte g = c.G;
                    byte b = c.B;

                    byte I = (byte)(0.3 * r + 0.59 * g + 0.11 * b);
                    Color c1 = Color.FromArgb(I, I, I);
                    bmp2.SetPixel(x, y, c1);
                }
            }
            pictureBox2.Image = bmp2;
            pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
        }

        private void pictureBox1_Click(object sender, EventArgs e) {
            bmp = new Bitmap(@"C:\pic.bmp");
            pictureBox1.Image = bmp;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            bmp2 = (Bitmap)bmp.Clone();
        }

        private void button2_Click(object sender, EventArgs e) {
            try {
                if (bmp2 != null) {
                    bmp2.Save(@"c:\test.bmp"); // <- this throws an exception every time and won't save anything
                }
            } catch (Exception ex) {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
    }
}

我让它弹出一个消息框窗口,告诉我错误是什么,并显示“GDI+ 中发生一般错误”。

【问题讨论】:

  • 保存在系统驱动器的根目录中不是一个好主意。尝试使用临时文件夹 (C:\TEMP\Test.bmp)

标签: c# winforms


【解决方案1】:

尝试改变加载图片的方式

using(FileStream fs = new FileStream(@"C:\temp\pic.bmp", FileMode.Open, FileAccess.Read))
{
    MemoryStream ms = new MemoryStream();
    fs.CopyTo(ms);
    ms.Seek(0, System.IO.SeekOrigin.Begin);
    bmp = (Bitmap)System.Drawing.Image.FromStream(ms);
}
pictureBox1.Image = bmp;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
bmp2 = (Bitmap)bmp.Clone();

请注意,这可能与您的问题无关,但最好避免写入系统驱动器的根目录。通常,此位置需要提升访问权限。

【讨论】:

  • 还有,都是因为我在根目录下。
【解决方案2】:

尝试将其保存到文件夹中,而不仅仅是 C:。否则,我认为您需要以管理员权限运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    相关资源
    最近更新 更多