dao@develop

在昆明的日子里~
posts - 1, comments - 15, trackbacks - 0, articles - 1
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理
从用 .Net Web 开发到现在所看到的略缩生成代码都不尽人意,要不太局限,要不失真厉害。

为此写了一个相对完善的函数供大家学习。

其中的 SaveIamge 函数提供了失真解决方法,对于处理过的图片(如加水印……)要求保持高品质可以直接调用。

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Text.RegularExpressions;

/// <summary>
// 图片处理。
// http://www.hulaka.com/
// (c) 2008 Dao
/// </summary>
public class Image
{
    
/// <summary>
    
/// 缩略模式。
    
/// </summary>
    public enum ThumbMode : byte
    {
        
/// <summary>
        
/// 完整模式
        
/// </summary>
        Full = 1,
        
/// <summary>
        
/// 最大尺寸
        
/// </summary>
        Max
    }

    
/// <summary>
    
/// 缩略图。
    
/// </summary>
    
/// <param name="image">要缩略的图片</param>
    
/// <param name="size">要缩放的尺寸</param>
    
/// <param name="mode">缩略模式</param>
    
/// <param name="contentAlignment">对齐方式</param>
    
/// <returns>返回已经缩放的图片。</returns>
    public static Bitmap Thumbnail(Bitmap image, Size size, ThumbMode mode, ContentAlignment contentAlignment)
    {
        
if (!size.IsEmpty && !image.Size.IsEmpty && !size.Equals(image.Size))
        {
            
//先取一个宽比例。
            double scale = (double)image.Width / (double)size.Width;
            
//缩略模式
            switch (mode)
            {
                
case ThumbMode.Full:
                    
if (image.Height > image.Width)
                        scale 
= (double)image.Height / (double)size.Height;
                    
break;
                
case ThumbMode.Max:
                    
if (image.Height / scale < size.Height)
                        scale 
= (double)image.Height / (double)size.Height;
                    
break;
            }
            SizeF newSzie 
= new SizeF((float)(image.Width / scale), (float)(image.Height / scale));
            Bitmap result 
= new Bitmap(size.Width, size.Height);
            
using (Graphics g = Graphics.FromImage(result))
            {
                g.FillRectangle(Brushes.White, 
new Rectangle(new Point(00), size));
                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 - size.Width) * 0.5), 0), newSzie);
                        
break;
                    
case ContentAlignment.TopRight:
                        destRect 
= new RectangleF(new PointF(-(float)(newSzie.Width - size.Width), 0), newSzie);
                        
break;
                    
case ContentAlignment.MiddleLeft:
                        destRect 
= new RectangleF(new PointF(0-(float)((newSzie.Height - size.Height) * 0.5)), newSzie);
                        
break;
                    
case ContentAlignment.MiddleCenter:
                        destRect 
= new RectangleF(new PointF(-(float)((newSzie.Width - size.Width) * 0.5), -(float)((newSzie.Height - size.Height) * 0.5)), newSzie);
                        
break;
                    
case ContentAlignment.MiddleRight:
                        destRect 
= new RectangleF(new PointF(-(float)(newSzie.Width - size.Width), -(float)((newSzie.Height - size.Height) * 0.5)), newSzie);
                        
break;
                    
case ContentAlignment.BottomLeft:
                        destRect 
= new RectangleF(new PointF(0-(float)(newSzie.Height - size.Height)), newSzie);
                        
break;
                    
case ContentAlignment.BottomCenter:
                        destRect 
= new RectangleF(new PointF(-(float)((newSzie.Width - size.Width) * 0.5), -(float)(newSzie.Height - size.Height)), newSzie);
                        
break;
                    
case ContentAlignment.BottomRight:
                        destRect 
= new RectangleF(new PointF(-(float)(newSzie.Width - size.Width), -(float)(newSzie.Height - size.Height)), newSzie);
                        
break;
                    
default:
                        destRect 
= new RectangleF(new PointF(00), newSzie);
                        
break;
                }
                g.DrawImage(image, destRect, 
new RectangleF(new PointF(0F, 0F), image.Size), GraphicsUnit.Pixel);
                image.Dispose();
            }
            
return result;
        }
        
else
            
return image;
    }

    
/// <summary>
    
/// 保存图片。
    
/// </summary>
    
/// <param name="image">要保存的图片</param>
    
/// <param name="quality">品质(1L~100L之间,数值越大品质越好)</param>
    
/// <param name="filename">保存路径</param>
    public static void SaveIamge(Bitmap image, long quality, string filename)
    {
        
using (EncoderParameters encoderParams = new EncoderParameters(1))
        {
            
using (EncoderParameter parameter = (encoderParams.Param[0= new EncoderParameter(Encoder.Quality, quality)))
            {
                ImageCodecInfo encoder 
= null;
                
//取得扩展名
                string ext = Path.GetExtension(filename);
                
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;
                    }
                }
                Directory.CreateDirectory(Path.GetDirectoryName(filename));
                image.Save(filename, encoder, encoderParams);
            }
        }
    }

    
/// <summary>
    
/// 保存图片。
    
/// </summary>
    
/// <param name="stream">要保存的流</param>
    
/// <param name="quality">品质(1L~100L之间,数值越大品质越好)</param>
    
/// <param name="filename">保存路径</param>
    public static void SaveIamge(Stream stream, long quality, string filename)
    {
        
using (Bitmap bmpTemp = new Bitmap(stream))
        {
            SaveIamge(bmpTemp, quality, filename);
        }
    }
}

调用方法如下:
using (Bitmap bmpAvatar = Image.Thumbnail(new Bitmap(/*<流,FileUpload 控件的 PostedFile.InputStream 属性>*/), new Size(4848), Image.ThumbMode.Full, ContentAlignment.MiddleCenter))
{
    Image.SaveIamge(bmpAvatar, 
95L, Server.MapPath("~/upfiles/Avatar.jpg"));
}


演示程序:



下载演示程序

Tag标签: 略缩,asp.net,C#

Feedback

#1楼    回复  引用  查看    

2008-02-24 18:13 by 米开狼基罗      
有没有样例啊?

#2楼    回复  引用    

2008-02-24 18:14 by 菲菲菲菲菲菲 [未注册用户]
用GIF老出问题

#3楼    回复  引用    

2008-02-24 18:32 by tmxkhd666 [未注册用户]
你写的很好啊.
有没有样例啊.
能不能向我的邮箱发一份啊.
谢谢兄弟啊.

#4楼    回复  引用  查看    

2008-02-24 21:38 by 笔笔VS小武      
这个不有写吗??
Image类就有这样的方法。
Image img=new Image()
img.GetThumbnailImage(newWidth, newHeigth, callback, new System.IntPtr());

#5楼 [楼主]   回复  引用  查看    

2008-02-24 22:29 by 刀晟容      
@笔笔VS小武
如果图片大小和你要求缩放的大小不一样的话(宽高比列刚好相反) GetThumbnailImage 拉伸的太严重了

#6楼    回复  引用  查看    

2008-02-25 08:27 by 无忧浪子      
学习.

#7楼    回复  引用  查看    

2008-02-25 09:19 by 亦续缘      
生成缩略图的时候能否保存为原图的原始扩展名(除GIF除外)???

#8楼    回复  引用  查看    

2008-02-25 09:24 by 李华顺      
@笔笔VS小武
楼主这种做法是实现最优化的切图,先缩小,再从中间取出来的图片是最合适的

#9楼    回复  引用  查看    

2008-02-25 13:49 by flyingchen      
性能如何

#10楼 [楼主]   回复  引用  查看    

2008-02-25 16:16 by 刀晟容      
@亦续缘

你可以通过 Path.GetExtension() 取得上传文件的扩展名,SaveIamge 函数会根据你的提供的扩展名以相关编码器保存图片。

#11楼 [楼主]   回复  引用  查看    

2008-02-25 16:30 by 刀晟容      
@flyingchen

性能还行。

不过也许还有最优的解决方法。

#12楼    回复  引用  查看    

2008-02-26 01:35 by 问天      
GetThumbnailImage 的最大问题是在于如果图片内嵌有缩略图的话,它会使用内嵌的这个缩略图而不是原图去生成图片,生成的效果惨不忍睹……

#13楼    回复  引用  查看    

2008-02-26 14:07 by jillzhang      
生成Gif动画缩略图-Gif动画水印的改进
http://www.cnblogs.com/jillzhang/archive/2008/02/24/1079794.html

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-02-25 01:14 编辑过
Google站内搜索


China-pub 计算机图书网上专卖店!6.5万品种 2-8折!
近千种 9-95 新二手计算图书火热销售中!

相关文章:


相关搜索:
略缩 asp.net C#

相关链接: