private Bitmap srcBitmap = null; private Bitmap showBitmap = null;
Read Image
Private void button1_click (Object sender, eventargs e) {openfiledialog = new openfiledialog (); openfiledialog. filter = @ "bitmap file | *. BMP | "+ @" Jpeg | *. JPG ;*. JPEG ;*. jpe ;*. jfif | "+ @" GIF | *. GIF | "+ @" tiff | *. TIF ;*. tiff | "+ @" PNG | *. PNG | "+ @" ICO | *. ICO | "+ @" all image files | "+ @"*. BMP ;*. JPG ;*. JPEG ;*. jpe ;*. jfif ;*. GIF ;*. TIF ;*. tiff ;*. PNG ;*. ICO | "+ @" all files | *. * "; openfiledialog. title = "open image file"; openfiledialog. filterindex = 7; If (dialogresult. OK = openfiledialog. showdialog () {srcbitmap = (Bitmap) bitmap. fromfile (openfiledialog. filename, false); showbitmap = srcbitmap; this. autoscroll = true; this. autoscrollminsize = new size (INT) (showbitmap. width), (INT) (showbitmap. height); this. invalidate ();}}
Show images
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (showBitmap != null) { Graphics g = e.Graphics; g.DrawImage(showBitmap, new Rectangle( this.AutoScrollPosition.X, this.AutoScrollPosition.Y, (int)(showBitmap.Width), (int)(showBitmap.Height))); } }
Save image
Private void button2_click (Object sender, eventargs e) {If (showbitmap = NULL) return; savefiledialog = new savefiledialog (); savefiledialog. filter = @ "bitmap file | *. BMP | "+ @" Jpeg | *. JPG | "+ @" GIF | *. GIF | "+ @" tiff | *. TIF | "+ @" PNG | *. PNG | "+ @" icon | *. ICO "; savefiledialog. filterindex = 2; savefiledialog. restoredirectory = true; If (dialogresult. OK = savefiledialog. showdialog () {imageformat format = imageformat. JPEG; Switch (path. getextension (savefiledialog. filename ). tolower () {Case ". BMP ": format = imageformat. BMP; break; case ". jpg ": format = imageformat. JPEG; break; case ". GIF ": format = imageformat. GIF; break; case ". TIF ": format = imageformat. tiff; break; case ". PNG ": format = imageformat. PNG; break; case ". ICO ": format = imageformat. icon; break; default: MessageBox. show (this, "unsupported image format was specified", "error", messageboxbuttons. OK, messageboxicon. error); return;} Try {showbitmap. save (savefiledialog. filename, format);} catch (exception) {MessageBox. show (this, "failed writing image file", "error", messageboxbuttons. OK, messageboxicon. error );}}}