C#圖片處理示例(裁剪,縮放,清晰度,水印)

前言算法

需求源自項目中的一些應用,好比相冊功能,一般用戶上傳相片後咱們都會針對該相片再生成一張縮略圖,用於其它頁面上的列表顯示。隨便看一下,大部分網站基本都是將原圖等比縮放來生成縮略圖。但完美主義者會發現一些問題,好比顯示排版時想讓相片縮略圖列表很是統1、整齊、和美觀,好比要求每張縮略圖大小固定爲120 x 90且不拉伸變形怎麼辦?再好比用戶頭像如何讓縮略圖比原圖更清晰?或是如何在上傳的圖片下加一個半透明的LOGO水印?數組

OK,本文根據本身的項目代碼描述以上問題的解決方案,所有基於.Net Framework類庫完成,代碼中包含了C#圖片處理的一些基礎知識.網絡

提升縮略圖清晰度ide

(原圖200*200,12.3k)(處理後80*80,17.7k)字體

以前一直認爲縮略圖不可能比原圖清晰,直到某天一位產品的同事給我看某網站的效果。因而開始尋找.NET下實現代碼,仔細觀察縮略圖確實比原圖更清晰了一些,但代價是縮略圖文件比原圖更大,因此若是你想讓一張佔滿顯示器屏幕的超大圖片更清晰,那麼圖片佔用空間和網絡流量就必需考慮了,若是是互聯網應用,建議縮略圖在200像素之內的使用該方法。固然若是哪位有更好的代碼即能讓圖片文件大小變化不大又讓圖片更清晰還請分享。網站

吳劍 http://www.cnblogs.com/wu-jian編碼

圖片裁剪spa

(原圖256*192)(裁剪要求100*100)3d

(原圖256*192)(裁剪要求90*120)code

(原圖256*192)(裁剪要求120*90)

(原圖146*256)(裁剪要求100*100)

(原圖146*256)(裁剪要求90*120)

(原圖146*256)(裁剪要求120*90)

算法:以原圖中心做爲裁剪中心,最大範圍的對原圖進行裁剪,而後對裁剪結果等比縮放。

吳劍 http://www.cnblogs.com/wu-jian

圖片水印

僅演示了效果,如須要變動字體、水印透明度、位置等可自行在代碼或方法中擴展。

代碼

封裝了幾個通用的方法,如發現有BUG或漏洞還請及時指正。

複製代碼
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace WuJian.Common
{
    /// <summary>
    /// 圖片處理
    /// http://www.cnblogs.com/wu-jian/
    /// 
    /// 吳劍 2011-02-20 建立
    /// 吳劍 2012-08-08 修改
    /// </summary>
    public class Image
    {
        #region 正方型裁剪並縮放

        /// <summary>
        /// 正方型裁剪
        /// 以圖片中心爲軸心,截取正方型,而後等比縮放
        /// 用於頭像處理
        /// </summary>
        /// <remarks>吳劍 2012-08-08</remarks>
        /// <param name="fromFile">原圖Stream對象</param>
        /// <param name="fileSaveUrl">縮略圖存放地址</param>
        /// <param name="side">指定的邊長(正方型)</param>
        /// <param name="quality">質量(範圍0-100)</param>
        public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality)
        {
            //建立目錄
            string dir = Path.GetDirectoryName(fileSaveUrl);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            //原始圖片(獲取原始圖片建立對象,並使用流中嵌入的顏色管理信息)
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原圖寬高均小於模版,不做處理,直接保存
            if (initImage.Width <= side && initImage.Height <= side)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //原始圖片的寬、高
                int initWidth = initImage.Width;
                int initHeight = initImage.Height;

                //非正方型先裁剪爲正方型
                if (initWidth != initHeight)
                {
                    //截圖對象
                    System.Drawing.Image pickedImage = null;
                    System.Drawing.Graphics pickedG = null;

                    //寬大於高的橫圖
                    if (initWidth > initHeight)
                    {
                        //對象實例化
                        pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                        //設置質量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                        Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
                        //畫圖
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置寬
                        initWidth = initHeight;
                    }
                    //高大於寬的豎圖
                    else
                    {
                        //對象實例化
                        pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                        //設置質量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                        Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
                        //畫圖
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置高
                        initHeight = initWidth;
                    }

                    //將截圖對象賦給原圖
                    initImage = (System.Drawing.Image)pickedImage.Clone();
                    //釋放截圖資源
                    pickedG.Dispose();
                    pickedImage.Dispose();
                }

                //縮略圖對象
                System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side);
                System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage);
                //設置質量
                resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //用指定背景色清空畫布
                resultG.Clear(Color.White);
                //繪製縮略圖
                resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel);

                //關鍵質量控制
                //獲取系統編碼類型數組,包含了jpeg,bmp,png,gif,tiff
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                //保存縮略圖
                resultImage.Save(fileSaveUrl, ici, ep);

                //釋放關鍵質量控制所用資源
                ep.Dispose();

                //釋放縮略圖資源
                resultG.Dispose();
                resultImage.Dispose();

                //釋放原始圖片資源
                initImage.Dispose();
            }
        }

        #endregion

        #region 自定義裁剪並縮放

        /// <summary>
        /// 指定長寬裁剪
        /// 按模版比例最大範圍的裁剪圖片並縮放至模版尺寸
        /// </summary>
        /// <remarks>吳劍 2012-08-08</remarks>
        /// <param name="fromFile">原圖Stream對象</param>
        /// <param name="fileSaveUrl">保存路徑</param>
        /// <param name="maxWidth">最大寬(單位:px)</param>
        /// <param name="maxHeight">最大高(單位:px)</param>
        /// <param name="quality">質量(範圍0-100)</param>
        public static void CutForCustom(System.IO.Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
        {
            //從文件獲取原始圖片,並使用流中嵌入的顏色管理信息
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原圖寬高均小於模版,不做處理,直接保存
            if (initImage.Width <= maxWidth && initImage.Height <= maxHeight)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //模版的寬高比例
                double templateRate = (double)maxWidth / maxHeight;
                //原圖片的寬高比例
                double initRate = (double)initImage.Width / initImage.Height;

                //原圖與模版比例相等,直接縮放
                if (templateRate == initRate)
                {
                    //按模版大小生成最終圖片
                    System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                    templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                //原圖與模版比例不等,裁剪後縮放
                else
                {
                    //裁剪對象
                    System.Drawing.Image pickedImage = null;
                    System.Drawing.Graphics pickedG = null;

                    //定位
                    Rectangle fromR = new Rectangle(0, 0, 0, 0);//原圖裁剪定位
                    Rectangle toR = new Rectangle(0, 0, 0, 0);//目標定位

                    //寬爲標準進行裁剪
                    if (templateRate > initRate)
                    {
                        //裁剪對象實例化
                        pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)System.Math.Floor(initImage.Width / templateRate));
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);

                        //裁剪源定位
                        fromR.X = 0;
                        fromR.Y = (int)System.Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
                        fromR.Width = initImage.Width;
                        fromR.Height = (int)System.Math.Floor(initImage.Width / templateRate);

                        //裁剪目標定位
                        toR.X = 0;
                        toR.Y = 0;
                        toR.Width = initImage.Width;
                        toR.Height = (int)System.Math.Floor(initImage.Width / templateRate);
                    }
                    //高爲標準進行裁剪
                    else
                    {
                        pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(initImage.Height * templateRate), initImage.Height);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);

                        fromR.X = (int)System.Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
                        fromR.Y = 0;
                        fromR.Width = (int)System.Math.Floor(initImage.Height * templateRate);
                        fromR.Height = initImage.Height;

                        toR.X = 0;
                        toR.Y = 0;
                        toR.Width = (int)System.Math.Floor(initImage.Height * templateRate);
                        toR.Height = initImage.Height;
                    }

                    //設置質量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //裁剪
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);

                    //按模版大小生成最終圖片
                    System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);

                    //關鍵質量控制
                    //獲取系統編碼類型數組,包含了jpeg,bmp,png,gif,tiff
                    ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo ici = null;
                    foreach (ImageCodecInfo i in icis)
                    {
                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                        {
                            ici = i;
                        }
                    }
                    EncoderParameters ep = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                    //保存縮略圖
                    templateImage.Save(fileSaveUrl, ici, ep);
                    //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

                    //釋放資源
                    templateG.Dispose();
                    templateImage.Dispose();

                    pickedG.Dispose();
                    pickedImage.Dispose();
                }
            }

            //釋放資源
            initImage.Dispose();
        }
        #endregion

        #region 等比縮放

        /// <summary>
        /// 圖片等比縮放
        /// </summary>
        /// <remarks>吳劍 2012-08-08</remarks>
        /// <param name="fromFile">原圖Stream對象</param>
        /// <param name="savePath">縮略圖存放地址</param>
        /// <param name="targetWidth">指定的最大寬度</param>
        /// <param name="targetHeight">指定的最大高度</param>
        /// <param name="watermarkText">水印文字(爲""表示不使用水印)</param>
        /// <param name="watermarkImage">水印圖片路徑(爲""表示不使用水印)</param>
        public static void ZoomAuto(System.IO.Stream fromFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage)
        {
            //建立目錄
            string dir = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            //原始圖片(獲取原始圖片建立對象,並使用流中嵌入的顏色管理信息)
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原圖寬高均小於模版,不做處理,直接保存
            if (initImage.Width <= targetWidth && initImage.Height <= targetHeight)
            {
                //文字水印
                if (watermarkText != "")
                {
                    using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage))
                    {
                        System.Drawing.Font fontWater = new Font("黑體", 10);
                        System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }

                //透明圖片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //獲取水印圖片
                        using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                        {
                            //水印繪製條件:原始圖片寬高均大於或等於水印圖片
                            if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height)
                            {
                                Graphics gWater = Graphics.FromImage(initImage);

                                //透明屬性
                                ImageAttributes imgAttributes = new ImageAttributes();
                                ColorMap colorMap = new ColorMap();
                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                ColorMap[] remapTable = { colorMap };
                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                                float[][] colorMatrixElements = { 
                                   new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  0.0f,  0.5f, 0.0f},//透明度:0.5
                                   new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                };

                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);

                                gWater.Dispose();
                            }
                            wrImage.Dispose();
                        }
                    }
                }

                //保存
                initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //縮略圖寬、高計算
                double newWidth = initImage.Width;
                double newHeight = initImage.Height;

                //寬大於高或寬等於高(橫圖或正方)
                if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
                {
                    //若是寬大於模版
                    if (initImage.Width > targetWidth)
                    {
                        //寬按模版,高按比例縮放
                        newWidth = targetWidth;
                        newHeight = initImage.Height * (targetWidth / initImage.Width);
                    }
                }
                //高大於寬(豎圖)
                else
                {
                    //若是高大於模版
                    if (initImage.Height > targetHeight)
                    {
                        //高按模版,寬按比例縮放
                        newHeight = targetHeight;
                        newWidth = initImage.Width * (targetHeight / initImage.Height);
                    }
                }

                //生成新圖
                //新建一個bmp圖片
                System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
                //新建一個畫板
                System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);

                //設置質量
                newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //置背景色
                newG.Clear(Color.White);
                //畫圖
                newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

                //文字水印
                if (watermarkText != "")
                {
                    using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage))
                    {
                        System.Drawing.Font fontWater = new Font("宋體", 10);
                        System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }

                //透明圖片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //獲取水印圖片
                        using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                        {
                            //水印繪製條件:原始圖片寬高均大於或等於水印圖片
                            if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height)
                            {
                                Graphics gWater = Graphics.FromImage(newImage);

                                //透明屬性
                                ImageAttributes imgAttributes = new ImageAttributes();
                                ColorMap colorMap = new ColorMap();
                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                ColorMap[] remapTable = { colorMap };
                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                                float[][] colorMatrixElements = { 
                                   new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  0.0f,  0.5f, 0.0f},//透明度:0.5
                                   new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                };

                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
                                gWater.Dispose();
                            }
                            wrImage.Dispose();
                        }
                    }
                }

                //保存縮略圖
                newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                //釋放資源
                newG.Dispose();
                newImage.Dispose();
                initImage.Dispose();
            }
        }

        #endregion

        #region 其它

        /// <summary>
        /// 判斷文件類型是否爲WEB格式圖片
        /// (注:JPG,GIF,BMP,PNG)
        /// </summary>
        /// <param name="contentType">HttpPostedFile.ContentType</param>
        /// <returns></returns>
        public static bool IsWebImage(string contentType)
        {
            if (contentType == "image/pjpeg" || contentType == "image/jpeg" || contentType == "image/gif" || contentType == "image/bmp" || contentType == "image/png")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

    }//end class
}
複製代碼
相關文章
相關標籤/搜索