日期:2014-05-17  浏览次数:20969 次

C#图片裁剪与缩放

C#图片裁剪与缩放

? 【参考】http://www.cnblogs.com/wu-jian/archive/2011/02/21/1959382.html

? 最近由于需要C#图片处理的相关应用,遂在网上参考一下,写出如下代码作为总结。

? 通常需要将图片缩放到指定宽度与高度的缩略图,若只对原图片进行缩放,当图片前后高宽比例不同时,缩放后的图片就会拉伸变形。可以采取的办法是先按照目标图片的高宽比进行裁剪,然后缩放到目标图片的高宽就ok了。

? 原理很简单:

? 1)首先根据目标图片的高宽比计算原图片的裁剪矩形区域

? 2)然后将该矩形区域内的图像拷贝到目标高宽的矩形区域中,下面上代码:

        /// <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);
        }

?