制作缩略图【摘录】

前段时间做的一个项目需要上传图片,同时上传的时候生成缩略图,恰好有人写了这么个类,于是修改了一下,现贴出来。

——————————————————

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;

/// <summary>
    /// 创建缩略图
    /// </summary>
    public class CreateBreviaryImage
    {
        private static Hashtable htmimes = new Hashtable();
        internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp";
        private string sExt = ".jpg";
        public CreateBreviaryImage()
        {
            htmimes[".jpe"] = "image/jpeg";
            htmimes[".jpeg"] = "image/jpeg";
            htmimes[".jpg"] = "image/jpeg";
            htmimes[".png"] = "image/png";
            htmimes[".tif"] = "image/tiff";
            htmimes[".tiff"] = "image/tiff";
            htmimes[".bmp"] = "image/bmp";

        }
        #region 生产缩略图
        /// <summary>
        /// 返回缩略图Size对象
        /// </summary>
        /// <param name="maxWidth">缩略图宽度</param>
        /// <param name="maxHeight">缩略图高度</param>
        /// <param name="width">原图宽度</param>
        /// <param name="height">原图高度</param>
        /// <returns>缩略图大小</returns>
        private Size NewSize(int maxWidth, int maxHeight, int width, int height)
        {
            double w = 0.0;
            double h = 0.0;
            double sw = Convert.ToDouble(width);
            double sh = Convert.ToDouble(height);
            double mw = Convert.ToDouble(maxWidth);
            double mh = Convert.ToDouble(maxHeight);

            if (sw < mw && sh < mh)
            {
                w = sw;
                h = sh;
            }
            else if ((sw / sh) > (mw / mh))
            {
                w = maxWidth;
                h = (w * sh) / sw;
            }
            else
            {
                h = maxHeight;
                w = (h * sw) / sh;
            }

            return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
        }

        /// <summary>
        /// 获取图像编码解码器的所有相关信息
        /// </summary>
        /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
        /// <returns>返回图像编码解码器的所有相关信息</returns>
        private static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }
        /// <summary>
        /// 检测扩展名的有效性
        /// </summary>
        /// <param name="sExt">文件名扩展名</param>
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
        private bool CheckValidExt(string sExt)
        {
            bool flag = false;
            string[] aExt = AllowExt.Split('|');
            foreach (string filetype in aExt)
            {
                if (filetype.ToLower() == sExt)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
        /// <summary>
        /// 保存缩略图到指定文件
        /// </summary>
        /// <param name="sourcePath">源图片路径(注意:绝对路径)</param>
        /// <param name="savePath">保存路径(注意:绝对路径)</param>
        /// <param name="newWith">缩略图宽度</param>
        /// <param name="newHeight">缩略图高度</param>
        public void SaveBreviaryImageTo(string sourcePath, string savePath, int newWith, int newHeight)
        {
            System.Drawing.Image image = CreateImage(
                                         sourcePath,
                                         newWith,
                                         newHeight);
            //设置 原图片 对象的 EncoderParameters 对象
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)100));
            image.Save(
                savePath,
                GetCodecInfo((string)htmimes[sExt]),
                parameters);
            parameters.Dispose();
        }
        /// <summary>
        /// 生产缩略图,获取缩略图的字节数组
        /// </summary>
        /// <param name="sourcePath">源图片路径(注意:绝对路径)</param>
        /// <param name="savePath">保存路径(注意:绝对路径)</param>
        /// <param name="newWith">缩略图宽度</param>
        /// <param name="newHeight">缩略图高度</param>
        public byte[] ReadNewImageBytes(string sourcePath,int newWith, int newHeight)
        {
            System.Drawing.Image image = CreateImage(
                                         sourcePath,
                                         newWith,
                                         newHeight);
            //设置 原图片 对象的 EncoderParameters 对象
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)100));

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            image.Save(
                stream,
                GetCodecInfo((string)htmimes[sExt]),
                parameters);
            stream.Position = 0;
            byte[] bytes= new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            parameters.Dispose();
            stream.Dispose();

            return bytes;
           
        }
            
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="sourceImagePath">***原图片路径(注意:绝对路径)***</param>
        /// <param name="maxWidth">缩略图的宽度</param>
        /// <param name="maxHeight">缩略图的高度</param>
        /// <param name="imageContentType">文件类型(MIME)的字符串</param>
        private Bitmap CreateImage(string SourceImagePath,int maxWidth, int maxHeight)
        {
            sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower();
            if (SourceImagePath.ToString() == System.String.Empty)
                throw new NullReferenceException("SourceImagePath is null!");
            if (!CheckValidExt(sExt))
            {
                throw new ArgumentException(
                    "原图片文件格式不正确,支持的格式有[ " + AllowExt + "]", "SourceImagePath");
            }
            //从 原图片 创建 Image 对象
            System.Drawing.Image image =
                System.Drawing.Image.FromFile(SourceImagePath);

            Size newSize = NewSize(maxWidth, maxHeight, image.Width, image.Height);
            //用指定的大小和格式初始化 Bitmap 类的新实例
            Bitmap bitmap = new Bitmap(newSize.Width, newSize.Height,PixelFormat.Format32bppArgb);
            //从指定的 Image 对象创建新 Graphics 对象
            Graphics g = Graphics.FromImage(bitmap);
            //清除整个绘图面并以透明背景色填充
            g.Clear(Color.Transparent);
           
            // 设置画布的描绘质量
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            //在指定位置并且按指定大小绘制 原图片 对象
            g.DrawImage(image, new Rectangle(0, 0, newSize.Width, newSize.Height),
            0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

            g.Dispose();
            image.Dispose();

            return bitmap;
           
        }
        #endregion
    }

——————————————————

posted @ 2006-04-24 23:41  meteorcui  阅读(190)  评论(0编辑  收藏  举报