c# 壓縮保存圖片


using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing.Imaging;
using System.Drawing;

/// <SUMMARY>
///MakeThum 的摘要說明
/// </SUMMARY>

namespace XinPai.Web
{
    public class MakeThum
    {
        public MakeThum()
        {
            //
            //TODO: 在此處添加構造函數邏輯
            //
        }

        /// <SUMMARY>
        /// 生成縮略圖//帶壓縮圖片不壓縮22k壓縮2k
        /// </SUMMARY>
        /// <PARAM name="originalImagePath" />原始路徑
        /// <PARAM name="thumbnailPath" />生成縮略圖路徑
        /// <PARAM name="width" />縮略圖的寬
        /// <PARAM name="height" />縮略圖的高
        //是否壓縮圖片質量
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, bool Ys)
        {
            //獲取原始圖片  
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            //縮略圖畫布寬高  
            int towidth = width;
            int toheight = height;
            //原始圖片寫入畫布座標和寬高(用來設置裁減溢出部分)  
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            //原始圖片畫布,設置寫入縮略圖畫布座標和寬高(用來原始圖片總體寬高縮放)  
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            //倍數變量  
            double multiple = 0;
            //獲取寬長的或是高長與縮略圖的倍數  
            if (originalImage.Width >= originalImage.Height)
                multiple = (double) originalImage.Width/(double) width;
            else
                multiple = (double) originalImage.Height/(double) height;
            //上傳的圖片的寬和高小等於縮略圖  
            if (ow <= width && oh <= height)
            {
                //縮略圖按原始寬高  
                bg_w = originalImage.Width;
                bg_h = originalImage.Height;
                //空白部分用背景色填充  
                bg_x = Convert.ToInt32(((double) towidth - (double) ow)/2);
                bg_y = Convert.ToInt32(((double) toheight - (double) oh)/2);
            }
                //上傳的圖片的寬和高大於縮略圖  
            else
            {
                //寬高按比例縮放  
                bg_w = Convert.ToInt32((double) originalImage.Width/multiple);
                bg_h = Convert.ToInt32((double) originalImage.Height/multiple);
                //空白部分用背景色填充  
                bg_y = Convert.ToInt32(((double) height - (double) bg_h)/2);
                bg_x = Convert.ToInt32(((double) width - (double) bg_w)/2);
            }
            //新建一個bmp圖片,並設置縮略圖大小.  
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一個畫板  
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //設置高質量插值法  
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            //設置高質量,低速度呈現平滑程度  
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空畫布並設置背景色  
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#FFF"));
            //在指定位置而且按指定大小繪製原圖片的指定部分  
            //第一個System.Drawing.Rectangle是原圖片的畫布座標和寬高,第二個是原圖片寫在畫布上的座標和寬高,最後一個參數是指定數值單位爲像素  
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h),
                new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            if (Ys)
            {
                System.Drawing.Imaging.ImageCodecInfo encoder = GetEncoderInfo("image/jpeg");
                try
                {
                    if (encoder != null)
                    {
                        System.Drawing.Imaging.EncoderParameters encoderParams =
                            new System.Drawing.Imaging.EncoderParameters(1);
                        //設置 jpeg 質量爲 60
                        encoderParams.Param[0] =
                            new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                                (long) 60);
                        bitmap.Save(thumbnailPath, encoder, encoderParams);
                        encoderParams.Dispose();
                    }
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }

            }
            else
            {

                try
                {
                    //獲取圖片類型  
                    string fileExtension = System.IO.Path.GetExtension(originalImagePath).ToLower();
                    //按原圖片類型保存縮略圖片,不按原格式圖片會出現模糊,鋸齒等問題.  
                    switch (fileExtension)
                    {
                        case ".gif":
                            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
                            break;
                        case ".jpg":
                            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        case ".bmp":
                            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp);
                            break;
                        case ".png":
                            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
                            break;
                    }
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }

            }

        }

        private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            //根據 mime 類型,返回編碼器
            System.Drawing.Imaging.ImageCodecInfo result = null;
            System.Drawing.Imaging.ImageCodecInfo[] encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < encoders.Length; i++)
            {
                if (encoders[i].MimeType == mimeType)
                {
                    result = encoders[i];
                    break;
                }
            }
            return result;
        }
    }
}
MakeThum:生成縮略圖類
        /// <summary>
        /// 加載圖片
        /// </summary>
        private void LoadImageFile()
        {
            var imageFileExePosition = Environment.CurrentDirectory;
            var imageFilePosition = imageFileExePosition + @"\ImageFile";

            try
            {
                var contentImageFile = imageFileExePosition + "\\Content\\ImageFile";
                if (Directory.Exists(contentImageFile))
                {
                    Directory.Delete(contentImageFile, true);
                }
                Directory.CreateDirectory(contentImageFile);

                var path = imageFilePosition;


                var types = new[] { "jpg", "jpeg", "png", "bmp" };
                foreach (var type in types)
                {
                    var imgPaths = Directory.GetFileSystemEntries(path, "*." + type, SearchOption.AllDirectories);
                    foreach (var img in imgPaths)
                    {

                        FileInfo f = new FileInfo(img);
                        var name = f.FullName.Replace("\\ImageFile", "\\Content\\ImageFile");

                        FileInfo f1 = new FileInfo(name);
                        if (!Directory.Exists(f1.DirectoryName))
                        {
                            Directory.CreateDirectory(f1.DirectoryName);
                        }
                        // f.CopyTo(name,true);


                        //if (!f.Name.Contains("min-"))
                        //{
                        //    if (f.Name.Contains("min"))
                        //    {
                        //        var name = f.FullName.Replace("\\min", "\\min-");
                        //        f.MoveTo(name);
                        //    }
                        //}
                        MakeThum.MakeThumbnail(f.FullName, name, 500, true);
                    }
                }

            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
相關文章
相關標籤/搜索