C#图片按比例缩放实例
本文实例为大家分享了C#图片按比例缩放的具体代码,供大家参考,具体内容如下
工具类代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Drawing; usingSystem.Drawing.Drawing2D; usingSystem.Drawing.Imaging; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceZoomImage.Utils { //////图片缩放 /// publicclassZoomImageUtil { //////图片缩放 /// ///图片 /// 目标宽度,若为0,表示宽度按比例缩放 /// 目标长度,若为0,表示长度按比例缩放 publicstaticBitmapGetThumbnail(Bitmapbmp,intwidth,intheight) { if(width==0) { width=height*bmp.Width/bmp.Height; } if(height==0) { height=width*bmp.Height/bmp.Width; } ImageimgSource=bmp; BitmapoutBmp=newBitmap(width,height); Graphicsg=Graphics.FromImage(outBmp); g.Clear(Color.Transparent); //设置画布的描绘质量 g.CompositingQuality=CompositingQuality.HighQuality; g.SmoothingMode=SmoothingMode.HighQuality; g.InterpolationMode=InterpolationMode.HighQualityBicubic; g.DrawImage(imgSource,newRectangle(0,0,width,height+1),0,0,imgSource.Width,imgSource.Height,GraphicsUnit.Pixel); g.Dispose(); imgSource.Dispose(); bmp.Dispose(); returnoutBmp; } } }
使用示例:
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.IO; usingSystem.Linq; usingSystem.Text; usingSystem.Threading; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; usingZoomImage.Utils; namespaceZoomImage { publicpartialclassForm1:Form { publicForm1() { InitializeComponent(); } privatevoidForm1_Load(objectsender,EventArgse) { openFileDialog1.Multiselect=true; } privatevoidtxtWidth_KeyPress(objectsender,KeyPressEventArgse) { if(e.KeyChar!=8&&!Char.IsDigit(e.KeyChar)) { e.Handled=true; } } privatevoidtxtHeight_KeyPress(objectsender,KeyPressEventArgse) { if(e.KeyChar!=8&&!Char.IsDigit(e.KeyChar)) { e.Handled=true; } } privatevoidbtnSelectImage_Click(objectsender,EventArgse) { try { if(txtWidth.Text==""&&txtHeight.Text=="") { return; } if(openFileDialog1.ShowDialog()==DialogResult.OK) { Task.Factory.StartNew(()=> { stringpath=Path.GetDirectoryName(openFileDialog1.FileNames[0])+"\\NewImage\\"; inti=0; foreach(stringfileNameinopenFileDialog1.FileNames) { Bitmapbmp=ZoomImageUtil.GetThumbnail(newBitmap(fileName),Convert.ToInt32(txtWidth.Text==""?"0":txtWidth.Text),Convert.ToInt32(txtHeight.Text==""?"0":txtHeight.Text)); if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.Delete(path+Path.GetFileName(fileName)); bmp.Save(path+Path.GetFileName(fileName)); this.Invoke(newInvokeDelegate(()=> { lblProgress.Text=string.Format("进度:{1}/{0}",openFileDialog1.FileNames.Length,++i); })); Thread.Sleep(1); } MessageBox.Show("成功!"); }); } } catch(Exceptionex) { MessageBox.Show(ex.Message); } } } //////跨线程访问控件的委托 /// publicdelegatevoidInvokeDelegate(); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。