user3559599
user3559599

Reputation:

Save an image in C#

I have code that's supposed to save a picture (Bitmap) and it doesn't save it and throws an exception every time, what is the problem?

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);
            }
        }
    }
}

I made it pop up a message box window telling me what the error is and it says "A generic error occured in GDI+".

Upvotes: 0

Views: 1642

Answers (2)

Steve
Steve

Reputation: 216243

Try to change the way in which you load your image

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();

Notice that it is probably unrelated to your problem but it is better to avoid writing in the root of your system drive. Usually this location requires elevated access permissions.

Upvotes: 2

Steve Dignan
Steve Dignan

Reputation: 8530

Try saving it to a folder instead of just C:. Otherwise, I think you need to run with admin privileges.

Upvotes: 1

Related Questions