對于一個網站來說,圖片顯示都是有一定的寬高比的,而客戶上傳的圖片大多未經過剪切,故上傳以后對圖片進行一定的剪切是非常必要的。
如此,我們應當剪一個類來完成這項工作。
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;}}
新聞熱點
疑難解答