Saving image in paint app c#
I am working on a simple paint app. I got everything working except save. I am doing all the paint operations inside a panel. I need to save it as an image. How to do thi开发者_运维知识库s?
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
Here is a great example of paint app: 1) WPF 2) WinForms
Something like this:
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);
}
}
If you're using wpf you can take alook at RenderTargetBitmap. It can render any visual into a bitmap that you can then save using @danyogiaxs awnser
-edit-
I also found this SO post for doing the same on winforms
精彩评论