首页 > 代码库 > 浅谈图片上传之剪切

浅谈图片上传之剪切

     对于一个网站来说,图片显示都是有一定的宽高比的,而客户上传的图片大多未经过剪切,故上传以后对图片进行一定的剪切是非常必要的。

如此,我们应当剪一个类来完成这项工作。

   


 public class ImageHelper{///图片宽高比,默认1.333 double _webWidth=1.333;/// <summary>///网站显示图片的 宽/高比/// </summary>public double WebWidth{get { return _webWidth; }set {_webWidth = value; }}/// <summary>/// 根据宽高比剪切图片,_webWidth/// </summary>/// <param name="img">需要剪切的图片</param>/// <returns></returns>public Bitmap CutImage(Bitmap img){int width = img.Width;int height = img.Height;Rectangle section = new Rectangle();//假如宽带高于高度图片if (width >= height){//根据网站宽高比例计算出宽度section.Width = (int)(height * _webWidth);//剪切宽大于原宽,取原宽if (section.Width > width)section.Width = width;section.Height = height;section.Y = 0;//计算出开始截图的X定位,计算方式为(原宽-剪切宽/2)section.X = (int)((width - section.Width) / 2);}///假如高度大于宽度的图片if (width < height){//根据宽高比计算出高度,为宽度/宽高比section.Height = (int)(width / _webWidth);//剪切宽大于原高,取原高if (section.Height > height)section.Height = height;section.Width = width;section.X = 0;//计算出开始截图的Y定位,计算方式为(原高-剪切高/2)section.Y = (int)((height - section.Height) / 2);}Bitmap pickedImage = new Bitmap(section.Width, section.Height);Graphics pickedG = Graphics.FromImage(pickedImage);//开始剪切并填充pickedG.DrawImage(img, new Rectangle(0, 0, section.Width, section.Height), section,GraphicsUnit.Pixel); return pickedImage;}}

 

 

 

  

浅谈图片上传之剪切