xp

导航

.net下生成高质量地缩略图

Posted on 2007-11-08 21:44  xp  阅读(1182)  评论(1编辑  收藏  举报
在生成缩略图地过程中,一开始利用.net 提供地GetThumbnailImage方法来实现,发现生成的有些图片质量很差。底是哪里出了问题呢,我们看下GetThumbnailImage方法在msdn上的说明:如果 Image 包含一个嵌入式缩略图像,则此方法会检索嵌入式缩略图,并将其缩放为所需大小。如果 Image 不包含嵌入式缩略图像,此方法会通过缩放主图像创建一个缩略图像。问题在于原照片上上,如果拿exif工具查看这张照片,你会发觉有一张160 * 120的缩略图包含在这张图片里面,因此GetThumbnailImage直接得到了这张缩略图返回了,而且因为我们要定义了大小,他实际上是把那张 160*120的缩略图放到我指定的大小后返回了。画质我们可以想象的到时多糟糕。
采用下面的方法可以得到质量很高的缩略图:

        using System.Drawing;
        using System.Drawing.Design;
        using System.Drawing.Drawing2D;
        using System.Drawing.Imaging;
        /// <summary>
        /// 产生缩略图
        /// </summary>
        /// <param name="original_image_file">源文件</param>
        /// <param name="object_width">缩略图宽度</param>
        /// <param name="object_height">缩略图高度</param>

        public static void GetThumbnailImage(string original_image_file, int object_width, int object_height)
        {
          

            int actual_width = 0;
            int actual_heigh = 0;
            string outputfilename = original_image_file + ".jpg";

            System.Drawing.Bitmap original_image = new Bitmap(original_image_file);//读取源文件          
            actual_width = original_image.Width;
            actual_heigh = original_image.Height;
           
            Bitmap img = new Bitmap(object_width, object_height);
            img.SetResolution(180f, 180f);
            Graphics gdiobj = Graphics.FromImage(img);
            gdiobj.CompositingQuality = CompositingQuality.HighQuality;
            gdiobj.SmoothingMode = SmoothingMode.HighQuality;
            gdiobj.InterpolationMode = InterpolationMode.HighQualityBicubic;
            gdiobj.PixelOffsetMode = PixelOffsetMode.HighQuality;

            gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0,object_width, object_height);
            Rectangle destrect = new Rectangle(0, 0,object_width, object_height);

            gdiobj.DrawImage(original_image, destrect, 0, 0, actual_width,actual_heigh, GraphicsUnit.Pixel);

            System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
            ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);

            System.Drawing.Imaging.ImageCodecInfo ici = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[0];

            if (ici != null)
            {
                img.Save(outputfilename, ici, ep);
               
            }
            else
            {
                img.Save(outputfilename, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

        }

    }