最近由於需要C#圖片處理的相關應用,遂在網上參考一下,寫出如下代碼作為總結。
通常需要將圖片縮放到指定寬度與高度的縮略圖,若只對原圖片進行縮放,當圖片前後高寬比例不同時,縮放後的圖片就會拉伸變形。可以采取的辦法是先按照目標圖片的高寬比進行裁剪,然後縮放到目標圖片的高寬就ok了。
原理很簡單:
1)首先根據目標圖片的高寬比計算原圖片的裁剪矩形區域
2)然後將該矩形區域內的圖像拷貝到目標高寬的矩形區域中,下面上代碼:
C#代碼
/// <summary>
/// 圖片轉換(裁剪並縮放)
/// </summary>
/// <param name="ASrcFileName">源文件名稱</param>
/// <param name="ADestFileName">目標文件名稱</param>
/// <param name="AWidth">轉換後的寬度(像素)</param>
/// <param name="AHeight">轉換後的高度(像素)</param>
/// <param name="AQuality">保存質量(取值在1-100之間)</param>
public static void DoConvert(string ASrcFileName, string ADestFileName, int AWidth, int AHeight, int AQuality)
{
Image ASrcImg = Image.FromFile(ASrcFileName);
if (ASrcImg.Width <= AWidth && ASrcImg.Height <= AHeight)
{//圖片的高寬均小於目標高寬,直接保存
ASrcImg.Save(ADestFileName);
return;
}
double ADestRate = AWidth * 1.0 / AHeight;
double ASrcRate = ASrcImg.Width * 1.0 / ASrcImg.Height;
//裁剪後的寬度
double ACutWidth = ASrcRate > ADestRate ? (ASrcImg.Height * ADestRate) : ASrcImg.Width;
//裁剪後的高度
double ACutHeight = ASrcRate > ADestRate ? ASrcImg.Height : (ASrcImg.Width / ADestRate);
//待裁剪的矩形區域,根據原圖片的中心進行裁剪
Rectangle AFromRect = new Rectangle(Convert.ToInt32((ASrcImg.Width - ACutWidth) / 2), Convert.ToInt32((ASrcImg.Height - ACutHeight) / 2), (int)ACutWidth, (int)ACutHeight);
//目標矩形區域
Rectangle AToRect = new Rectangle(0, 0, AWidth, AHeight);
Image ADestImg = new Bitmap(AWidth, AHeight);
Graphics ADestGraph = Graphics.FromImage(ADestImg);
ADestGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
ADestGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
ADestGraph.DrawImage(ASrcImg, AToRect, AFromRect, GraphicsUnit.Pixel);
//獲取系統image/jpeg編碼信息
ImageCodecInfo[] AInfos = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo AInfo = null;
foreach (ImageCodecInfo i in AInfos)
{
if (i.MimeType == "image/jpeg")
{
AInfo = i;
break;
}
}
//設置轉換後圖片質量參數
EncoderParameters AParams = new EncoderParameters(1);
AParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)AQuality);
//保存
ADestImg.Save(ADestFileName, AInfo, AParams);
}