Saving an image in a C # drawing application

I am working on a simple drawing application. Everything works for me, except for saving. I do all the paint operations inside the panel. I need to save it as an image. How to do it?

+3
source share
4 answers

Use this code

Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);//to create bmp of same size as panel
Rectangle rect=new Rectangle(0,0,panel1.Width,panel1.Height); //to set bounds to image
panel1.DrawToBitmap(bmp,rect);      // drawing panel1 imgae into bmp of bounds of rect
bmp.Save("C:\\a.png", System.Drawing.Imaging.ImageFormat.Png); //save location and type
+7
source

Here is a great example drawing application: 1) WPF 2) WinForms

+2
source

- :

public void SaveAs()
    {
        SaveFileDialog diag = new SaveFileDialog();
        DialogResult dr = diag.ShowDialog();

        if (dr.Equals(DialogResult.OK))
        {

            string _filename = diag.FileName;

            // filename not specified. Use FileName = ...
            if (_filename == null || _filename.Length == 0)
                throw new Exception("Unspecified file name");

            // cannot override RO file
            if (File.Exists(_filename)
                && (File.GetAttributes(_filename)
                & FileAttributes.ReadOnly) != 0)
                throw new Exception("File exists and is read-only!");

            // check supported image formats
            ImageFormat format = FormatFromExtension(_filename);
            if (format == null)
                throw new Exception("Unsupported image format");

            // JPG images get special treatement
            if (format.Equals(ImageFormat.Jpeg))
            {
                EncoderParameters oParams = new EncoderParameters(1);
                oParams.Param[0] = new EncoderParameter(
                    System.Drawing.Imaging.Encoder.Quality, 100L);
                ImageCodecInfo oCodecInfo = GetEncoderInfo("image/jpeg");
                yourImage.Save(_filename, oCodecInfo, oParams);
            }
            else
                yourImage.Save(_filename, format);

        }
    }
+1

wpf, alook RenderTargetBitmap. , @danyogiaxs awnser

-edit -

SO , winforms

+1

All Articles