コード例 #1
1
        public static void Resize(this Image source, String newFilename, Size newSize, long quality, ContentAlignment contentAlignment, ThumbMode mode)
        {
            Image image = source.Resize(newSize, quality, contentAlignment, mode);

            using (EncoderParameters encoderParams = new EncoderParameters(1))
            {
                using (EncoderParameter parameter = (encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality)))
                {
                    ImageCodecInfo encoder = null;
                    //取得擴展名
                    string ext = Path.GetExtension(newFilename);
                    if (string.IsNullOrEmpty(ext))
                        ext = ".jpg";
                    //根據擴展名得到解碼、編碼器
                    foreach (ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders())
                    {
                        if (Regex.IsMatch(codecInfo.FilenameExtension, string.Format(@"(;|^)\*\{0}(;|$)", ext), RegexOptions.IgnoreCase))
                        {
                            encoder = codecInfo;
                            break;
                        }
                    }

                    DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(newFilename));
                    if(dir.Exists == false) dir.Create();
                    image.Save(newFilename, encoder, encoderParams);
                }
            }
        }
コード例 #2
0
        public static Image Resize(this Image source, Size newSize, long quality, ContentAlignment contentAlignment, ThumbMode mode)
        {
            //Reference: http://www.cnblogs.com/dao/archive/2008/02/24/1079571.html
            if (newSize.IsEmpty || source.Size.IsEmpty) return source;

            //先取一個寬比例。
            double scale = (double)source.Width / (double)newSize.Width;

            //縮略模式
            switch (mode)
            {
                case ThumbMode.Full:
                    if (source.Height > source.Width)
                        scale = (double)source.Height / (double)newSize.Height;
                    break;
                case ThumbMode.Max:
                    if (source.Height / scale < newSize.Height)
                        scale = (double)source.Height / (double)newSize.Height;
                    break;
            }

            SizeF newSzie = new SizeF((float)(source.Width / scale), (float)(source.Height / scale));
            Bitmap newImage = new Bitmap(newSize.Width, newSize.Height);

            if(!source.PropertyItems.IsNullOrEmpty())
            {
                foreach (PropertyItem propertyItem in source.PropertyItems)
                {
                    newImage.SetPropertyItem(propertyItem);
                }
            }

            using (Graphics g = Graphics.FromImage(newImage))
            {
                g.FillRectangle(Brushes.White, new Rectangle(new Point(0, 0), newSize));
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.CompositingMode = CompositingMode.SourceOver;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                //對齊方式
                RectangleF destRect;
                switch (contentAlignment)
                {
                    case ContentAlignment.TopCenter:
                        destRect = new RectangleF(new PointF(-(float)((newSzie.Width - newSize.Width) * 0.5), 0), newSzie);
                        break;
                    case ContentAlignment.TopRight:
                        destRect = new RectangleF(new PointF(-(float)(newSzie.Width - newSize.Width), 0), newSzie);
                        break;
                    case ContentAlignment.MiddleLeft:
                        destRect = new RectangleF(new PointF(0, -(float)((newSzie.Height - newSize.Height) * 0.5)), newSzie);
                        break;
                    case ContentAlignment.MiddleCenter:
                        destRect = new RectangleF(new PointF(-(float)((newSzie.Width - newSize.Width) * 0.5), -(float)((newSzie.Height - newSize.Height) * 0.5)), newSzie);
                        break;
                    case ContentAlignment.MiddleRight:
                        destRect = new RectangleF(new PointF(-(float)(newSzie.Width - newSize.Width), -(float)((newSzie.Height - newSize.Height) * 0.5)), newSzie);
                        break;
                    case ContentAlignment.BottomLeft:
                        destRect = new RectangleF(new PointF(0, -(float)(newSzie.Height - newSize.Height)), newSzie);
                        break;
                    case ContentAlignment.BottomCenter:
                        destRect = new RectangleF(new PointF(-(float)((newSzie.Width - newSize.Width) * 0.5), -(float)(newSzie.Height - newSize.Height)), newSzie);
                        break;
                    case ContentAlignment.BottomRight:
                        destRect = new RectangleF(new PointF(-(float)(newSzie.Width - newSize.Width), -(float)(newSzie.Height - newSize.Height)), newSzie);
                        break;
                    default:
                        destRect = new RectangleF(new PointF(0, 0), newSzie);
                        break;
                }
                g.DrawImage(source, destRect, new RectangleF(new PointF(0F, 0F), source.Size), GraphicsUnit.Pixel);

                //source.Dispose();
            }

            return newImage;
        }
コード例 #3
0
        public long MakeThumbnailPicAndReturnSize(string originalImagePath, string thumbnailPath, int width, int height, ThumbMode mode, int imageQuality,
                                                  out int realWidth, out int realHeight, IDictionary <int, string> exifInfos)
        {
            int towidth  = width;
            int toheight = height;
            int x        = 0;
            int y        = 0;

            using (Image originalImage = Image.FromFile(originalImagePath, true))
            {
                if (exifInfos == null)
                {
                    exifInfos = new Dictionary <int, string>();
                    try
                    {
                        ProcessExifInfo(originalImage, exifInfos);
                    }
                    catch
                    {
                    }
                }

                int ow = originalImage.Width;
                int oh = originalImage.Height;
                switch (mode)
                {
                case ThumbMode.NHW:
                    if (toheight > originalImage.Height && towidth > originalImage.Width)
                    {
                        towidth  = originalImage.Width;
                        toheight = originalImage.Height;
                    }
                    else
                    {
                        if ((double)originalImage.Width / (double)towidth > (double)originalImage.Height / (double)toheight)
                        {
                            toheight = originalImage.Height * width / originalImage.Width;
                        }
                        else
                        {
                            towidth = originalImage.Width * height / originalImage.Height;
                        }
                    }
                    break;

                case ThumbMode.HW:
                    break;

                case ThumbMode.W:
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;

                case ThumbMode.H:
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;

                case ThumbMode.Cut:
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y  = 0;
                        x  = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x  = 0;
                        y  = (originalImage.Height - oh) / 2;
                    }
                    break;

                default:
                    break;
                }

                realWidth  = towidth;
                realHeight = toheight;

                //TODO:edit这里
                if (_generater != null)
                {
                    Logger.Debug("执行imagemagic");
                    _generater.Generater(new ThumbnailRequest
                    {
                        Height                = toheight < 1 ? new int?() : toheight,
                        Width                 = realWidth,
                        ImageQuality          = imageQuality,
                        OriginalImageFullName = originalImagePath,
                        SaveImageFullName     = thumbnailPath,
                        ThumbMode             = mode
                    });

                    return(new FileInfo(thumbnailPath).Length);
                }
                else
                {
                    Logger.Debug("imagemagic = null");
                }

                using (Image bitmap = new System.Drawing.Bitmap(towidth, toheight))
                {
                    var wrapMode = new ImageAttributes();
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);


                    using (var g = System.Drawing.Graphics.FromImage(bitmap))
                    {
                        g.Clear(Color.White);
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                        g.SmoothingMode      = SmoothingMode.HighQuality;

                        g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), x, y, ow, oh, GraphicsUnit.Pixel, wrapMode);

                        var encoderParms = new EncoderParameters(1);

                        encoderParms.Param[0] = new EncoderParameter(Encoder.Quality, imageQuality);

                        bitmap.Save(thumbnailPath, JpegFormat, encoderParms);

                        return(new FileInfo(thumbnailPath).Length);
                    }
                }
            }
        }
コード例 #4
0
 public void MakeThumbnailPic(string originalImagePath, string thumbnailPath, int width, int height, ThumbMode mode, int imageQuality)
 {
     MakeThumbnailPicAndReturnSize(originalImagePath, thumbnailPath, width, height, mode, imageQuality);
 }
コード例 #5
0
        public long MakeThumbnailPicAndReturnSize(string originalImagePath, string thumbnailPath, int width, int height, ThumbMode mode, int imageQuality)
        {
            int realHeight;
            int realWidht;
            IDictionary <int, string> exifs = new Dictionary <int, string>();

            return(MakeThumbnailPicAndReturnSize(originalImagePath, thumbnailPath, width, height, mode, imageQuality, out realWidht, out realHeight, exifs));
        }
コード例 #6
0
ファイル: Thumbnail.cs プロジェクト: huayumeng/ytoo.service
        public long MakeThumbnailPicAndReturnSize(string originalImagePath, string thumbnailPath, int width, int height, ThumbMode mode, int imageQuality,
            out int realWidth, out int realHeight, IDictionary<int, string> exifInfos)
        {
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;

            using (Image originalImage = Image.FromFile(originalImagePath, true))
            {

                if (exifInfos == null)
                {
                    exifInfos = new Dictionary<int, string>();
                    try
                    {
                        ProcessExifInfo(originalImage, exifInfos);
                    }
                    catch
                    {

                    }
                }

                int ow = originalImage.Width;
                int oh = originalImage.Height;
                switch (mode)
                {
                    case ThumbMode.NHW:
                        if (toheight > originalImage.Height && towidth > originalImage.Width)
                        {
                            towidth = originalImage.Width;
                            toheight = originalImage.Height;
                        }
                        else
                        {
                            if ((double)originalImage.Width / (double)towidth > (double)originalImage.Height / (double)toheight)
                            {
                                toheight = originalImage.Height * width / originalImage.Width;
                            }
                            else
                            {
                                towidth = originalImage.Width * height / originalImage.Height;
                            }
                        }
                        break;
                    case ThumbMode.HW:
                        break;
                    case ThumbMode.W:
                        toheight = originalImage.Height * width / originalImage.Width;
                        break;
                    case ThumbMode.H:
                        towidth = originalImage.Width * height / originalImage.Height;
                        break;
                    case ThumbMode.Cut:
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                            ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }

                realWidth = towidth;
                realHeight = toheight;

                //TODO:edit这里
                if (_generater != null)
                {
                    Logger.Debug("执行imagemagic");
                    _generater.Generater(new ThumbnailRequest
                    {
                        Height = toheight < 1 ? new int?() : toheight,
                        Width = realWidth,
                        ImageQuality = imageQuality,
                        OriginalImageFullName = originalImagePath,
                        SaveImageFullName = thumbnailPath,
                        ThumbMode = mode
                    });

                    return new FileInfo(thumbnailPath).Length;
                }
                else
                {
                    Logger.Debug("imagemagic = null");
                }

                using (Image bitmap = new System.Drawing.Bitmap(towidth, toheight))
                {
                    var wrapMode = new ImageAttributes();
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);


                    using (var g = System.Drawing.Graphics.FromImage(bitmap))
                    {
                        g.Clear(Color.White);
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        g.SmoothingMode = SmoothingMode.HighQuality;

                        g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), x, y, ow, oh, GraphicsUnit.Pixel, wrapMode);

                        var encoderParms = new EncoderParameters(1);

                        encoderParms.Param[0] = new EncoderParameter(Encoder.Quality, imageQuality);

                        bitmap.Save(thumbnailPath, JpegFormat, encoderParms);

                        return new FileInfo(thumbnailPath).Length;
                    }
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// 加载配置文件
        /// </summary>
        /// <param name="filePath"></param>
        private void LoadConfig(string filePath)
        {
            XmlDocument doc = new XmlDocument();

            try
            {
                doc.Load(filePath);
            }
            catch
            {
                throw new Exception("无法加载配置文件。必须把配置文件upload.config存放在根目录的/Config文件夹中。");
            }
            XmlNode root = doc.SelectSingleNode("config/items");

            if (root.ChildNodes != null)
            {
                ConfigItem item = null;
                foreach (XmlNode node in root.ChildNodes)
                {
                    if (node.NodeType == XmlNodeType.Element && node.LocalName == "item")
                    {
                        item = new ConfigItem();
                        ///循环读取属性
                        XmlAttributeCollection attrs = node.Attributes;
                        if (attrs.Count > 0)
                        {
                            foreach (XmlAttribute attr in attrs)
                            {
                                if (attr.Name.ToLower() == "code")
                                {
                                    item.Code = attr.Value;
                                }
                                if (attr.Name.ToLower() == "savepath")
                                {
                                    item.SavePath = attr.Value;
                                }
                                if (attr.Name.ToLower() == "thumb")
                                {
                                    item.Thumb = attr.Value;
                                    List <ThumbMode> modeList = new List <ThumbMode>();
                                    string[]         list     = item.Thumb.Split('|');
                                    for (int i = 0, len = list.Length; i < len; i++)
                                    {
                                        string[]  thumb = list[i].Split(',');
                                        ThumbMode mode  = new ThumbMode();
                                        mode.Mode   = thumb[0];
                                        mode.Width  = int.Parse(thumb[1]);
                                        mode.Height = int.Parse(thumb[2]);
                                        if (thumb.Length > 3)
                                        {
                                            mode.IsDraw = int.Parse(thumb[3]);
                                        }
                                        modeList.Add(mode);
                                    }
                                    item.ModeList = modeList;
                                }
                                if (attr.Name.ToLower() == "desc")
                                {
                                    item.Description = attr.Value;
                                }
                            }
                            cList.Add(item);
                        }
                    }
                }
            }
        }
コード例 #8
0
ファイル: Thumbnail.cs プロジェクト: huayumeng/ytoo.service
        public long MakeThumbnailPicAndReturnSize(string originalImagePath, string thumbnailPath, int width, int height, ThumbMode mode, int imageQuality)
        {
            int realHeight;
            int realWidht;
            IDictionary<int, string> exifs = new Dictionary<int, string>();

            return MakeThumbnailPicAndReturnSize(originalImagePath, thumbnailPath, width, height, mode, imageQuality, out realWidht, out realHeight, exifs);
        }
コード例 #9
0
ファイル: Thumbnail.cs プロジェクト: huayumeng/ytoo.service
 public void MakeThumbnailPic(string originalImagePath, string thumbnailPath, int width, int height, ThumbMode mode, int imageQuality)
 {
     MakeThumbnailPicAndReturnSize(originalImagePath, thumbnailPath, width, height, mode, imageQuality);
 }
コード例 #10
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="sourceImagePath">源图路径(带文件名的完整物理路径)</param>
        /// <param name="thumbImagePath">缩略图路径(带文件名的完整物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="thumbMode">生成缩略图的方式</param>
        public static void MakeThumb(string sourceImagePath, string thumbImagePath, int width, int height, ThumbMode thumbMode)
        {
            if (string.IsNullOrEmpty(sourceImagePath))
            {
                throw new SourceImagePathIsNullOrEmptyException();
            }

            if (!File.Exists(sourceImagePath))
            {
                throw new SourceFileNotExistException();
            }

            if (string.IsNullOrEmpty(thumbImagePath))
            {
                throw new ThumbImagePathIsNullOrEmptyException();
            }
            string directory = Path.GetDirectoryName(thumbImagePath);

            if (!Directory.Exists(directory))
            {
                throw new ThumbImagePathNotExistException();
            }

            try
            {
                using (Image sourceImage = Image.FromFile(sourceImagePath))
                {
                    if (width <= 0 && width >= sourceImage.Width)
                    {
                        throw new ThumbImageWidthIsErrorException();
                    }

                    if (height <= 0 && height >= sourceImage.Height)
                    {
                        throw new ThumbImageHeigthIsErrorException();
                    }

                    int towidth  = width;
                    int toheight = height;

                    int x  = 0;
                    int y  = 0;
                    int ow = sourceImage.Width;
                    int oh = sourceImage.Height;

                    switch (thumbMode)
                    {
                    case ThumbMode.HW:    //指定高宽缩放(不变形)
                        int tempheight = sourceImage.Height * width / sourceImage.Width;
                        if (tempheight > height)
                        {
                            towidth = sourceImage.Width * height / sourceImage.Height;
                        }
                        else
                        {
                            toheight = sourceImage.Height * width / sourceImage.Width;
                        }
                        break;

                    case ThumbMode.W:    //指定宽,高按比例
                        toheight = sourceImage.Height * width / sourceImage.Width;
                        break;

                    case ThumbMode.H:    //指定高,宽按比例
                        towidth = sourceImage.Width * height / sourceImage.Height;
                        break;

                    case ThumbMode.CUT:    //指定高宽裁减(不变形)
                        if ((double)sourceImage.Width / (double)sourceImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = sourceImage.Height;
                            ow = sourceImage.Height * towidth / toheight;
                            y  = 0;
                            x  = (sourceImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = sourceImage.Width;
                            oh = sourceImage.Width * height / towidth;
                            x  = 0;
                            y  = (sourceImage.Height - oh) / 2;
                        }
                        break;
                    }

                    //新建一个bmp图片
                    using (Image bitmap = new Bitmap(towidth, toheight))
                    {
                        //新建一个画板
                        using (Graphics g = Graphics.FromImage(bitmap))
                        {
                            //设置高质量插值法
                            g.InterpolationMode = InterpolationMode.High;

                            //设置高质量,低速度呈现平滑程度
                            g.SmoothingMode = SmoothingMode.HighQuality;

                            //清空画布并以透明背景色填充
                            g.Clear(Color.Transparent);

                            //在指定位置并且按指定大小绘制原图片的指定部分
                            g.DrawImage(sourceImage, new Rectangle(0, 0, towidth, toheight),
                                        new Rectangle(x, y, ow, oh),
                                        GraphicsUnit.Pixel);
                        }

                        //验证缩略图的保存路径是否带有文件名,如果没有带文件名则用 thumb_原文件名
                        if (!Regex.IsMatch(thumbImagePath, @"[^\\\/:\*\?""<>\|]+\.[^\\\/:\*\?""<>\|]+$", RegexOptions.Compiled))
                        {
                            thumbImagePath = thumbImagePath + "thumb_" + sourceImagePath.Remove(0, sourceImagePath.LastIndexOf(@"\") + 1);
                        }

                        //以源文件相同的格式保存缩略图
                        bitmap.Save(thumbImagePath, sourceImage.RawFormat);
                    }
                }
            }
            catch (OutOfMemoryException)
            {
                throw new SourceFileIsNotImageException();
            }
        }
コード例 #11
0
ファイル: ThumbnailService.cs プロジェクト: kavilee2012/lzQA
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="sourceImagePath">源图路径(带文件名的完整物理路径)</param>
        /// <param name="thumbImagePath">缩略图路径(带文件名的完整物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="thumbMode">生成缩略图的方式</param>    
        public static void MakeThumb(string sourceImagePath, string thumbImagePath, int width, int height, ThumbMode thumbMode)
        {
            if (string.IsNullOrEmpty(sourceImagePath))
            {
                throw new SourceImagePathIsNullOrEmptyException();
            }

            if (!File.Exists(sourceImagePath))
            {
                throw new SourceFileNotExistException();
            }

            if (string.IsNullOrEmpty(thumbImagePath))
            {
                throw new ThumbImagePathIsNullOrEmptyException();
            }
            string directory = Path.GetDirectoryName(thumbImagePath);
            if (!Directory.Exists(directory))
            {
                throw new ThumbImagePathNotExistException();
            }

            try
            {
                using (Image sourceImage = Image.FromFile(sourceImagePath))
                {

                    if (width <= 0 && width >= sourceImage.Width)
                    {
                        throw new ThumbImageWidthIsErrorException();
                    }

                    if (height <= 0 && height >= sourceImage.Height)
                    {
                        throw new ThumbImageHeigthIsErrorException();
                    }

                    int towidth = width;
                    int toheight = height;

                    int x = 0;
                    int y = 0;
                    int ow = sourceImage.Width;
                    int oh = sourceImage.Height;

                    switch (thumbMode)
                    {
                        case ThumbMode.HW://指定高宽缩放(不变形)
                            int tempheight = sourceImage.Height * width / sourceImage.Width;
                            if (tempheight > height)
                            {
                                towidth = sourceImage.Width * height / sourceImage.Height;
                            }
                            else
                            {
                                toheight = sourceImage.Height * width / sourceImage.Width;
                            }
                            break;
                        case ThumbMode.W://指定宽,高按比例
                            toheight = sourceImage.Height * width / sourceImage.Width;
                            break;
                        case ThumbMode.H://指定高,宽按比例
                            towidth = sourceImage.Width * height / sourceImage.Height;
                            break;
                        case ThumbMode.CUT://指定高宽裁减(不变形)
                            if ((double)sourceImage.Width / (double)sourceImage.Height > (double)towidth / (double)toheight)
                            {
                                oh = sourceImage.Height;
                                ow = sourceImage.Height * towidth / toheight;
                                y = 0;
                                x = (sourceImage.Width - ow) / 2;
                            }
                            else
                            {
                                ow = sourceImage.Width;
                                oh = sourceImage.Width * height / towidth;
                                x = 0;
                                y = (sourceImage.Height - oh) / 2;
                            }
                            break;
                    }

                    //新建一个bmp图片
                    using (Image bitmap = new Bitmap(towidth, toheight))
                    {

                        //新建一个画板
                        using (Graphics g = Graphics.FromImage(bitmap))
                        {

                            //设置高质量插值法
                            g.InterpolationMode = InterpolationMode.High;

                            //设置高质量,低速度呈现平滑程度
                            g.SmoothingMode = SmoothingMode.HighQuality;

                            //清空画布并以透明背景色填充
                            g.Clear(Color.Transparent);

                            //在指定位置并且按指定大小绘制原图片的指定部分
                            g.DrawImage(sourceImage, new Rectangle(0, 0, towidth, toheight),
                                new Rectangle(x, y, ow, oh),
                                GraphicsUnit.Pixel);
                        }

                        //验证缩略图的保存路径是否带有文件名,如果没有带文件名则用 thumb_原文件名
                        if (!Regex.IsMatch(thumbImagePath, @"[^\\\/:\*\?""<>\|]+\.[^\\\/:\*\?""<>\|]+$", RegexOptions.Compiled))
                        {
                            thumbImagePath = thumbImagePath + "thumb_" + sourceImagePath.Remove(0, sourceImagePath.LastIndexOf(@"\") + 1);
                        }

                        //以源文件相同的格式保存缩略图
                        bitmap.Save(thumbImagePath, sourceImage.RawFormat);
                    }
                }
            }
            catch (OutOfMemoryException)
            {
                throw new SourceFileIsNotImageException();
            }
        }
コード例 #12
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        /// <param name="DeleteOld">是否删除源文件</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, ThumbMode mode, bool DeleteOld)
        {
            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;

            switch (mode.ToString())
            {
            case "HW":    //指定高宽缩放(可能变形)
                break;

            case "W":    //指定宽,高按比例
                toheight = originalImage.Height * width / originalImage.Width;
                break;

            case "H":    //指定高,宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;

            case "Cut":    //指定高宽裁减(不变形)
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }

            //新建一个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.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);

            try
            {
                originalImage.Dispose();
                g.Dispose();
                if (DeleteOld)
                {
                    FileInfo fi = new FileInfo(originalImagePath);
                    fi.Delete();
                }
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(bitmap);
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                bitmap.Dispose();
            }
        }