Coding无限生成缩略图
Coding无限生成缩略图
using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Configuration;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace function
{
/// <summary>
/// DrawImg 的摘要说明。
/// </summary>
public class DrawImg
{
HttpContext context = HttpContext.Current;
private bool _cut_it=false;
public bool cut_it
{
get
{
return _cut_it;
}
set
{
_cut_it=value;
}
}
/// <summary>
/// 生成略缩图
/// </summary>
/// <param name="width">宽度</param>
/// <param name="height">裁剪高度</param>
/// <param name="file">原文件</param>
/// <param name="save_file">保存文件</param>
public void Set_ThumbnailImage(int clientWidth,int clientHeight,string file,string save_file)
{
System.Drawing.Image image,newimage;
System.Drawing.Image.GetThumbnailImageAbort callb = null;
image=System.Drawing.Image.FromFile(context.Server.MapPath(file));
float imagePretiveWidth = image.Width;//宽度
float imagePretiveHeight = image.Height;//高度
clientWidth = Math.Abs(clientWidth);
clientHeight = Math.Abs(clientHeight);
int imageWidth;
int imageHeight;
imageWidth = clientWidth;
if(imageWidth > imagePretiveWidth)
{
imageWidth =(int)imagePretiveWidth;
imageHeight = (int)imagePretiveHeight;
}
else
imageHeight = (int)(imagePretiveHeight*imageWidth/imagePretiveWidth);
//生成缩略图
newimage=image.GetThumbnailImage(imageWidth,imageHeight,callb,new System.IntPtr());
if(cut_it && imagePretiveHeight>clientHeight)
{
Bitmap bit = new Bitmap(newimage);
Rectangle rec = new Rectangle(); //构造一个Rectangle类,一个矩形
rec.Width = clientWidth;
rec.Height = clientHeight;
Bitmap bt1=bit.Clone(rec, PixelFormat.DontCare);
//bt1.Save(context.Server.MapPath(save_file), System.Drawing.Imaging.ImageFormat.Jpeg);
System.Drawing.Imaging.ImageCodecInfo myImageCodecInfo;
System.Drawing.Imaging.Encoder myEncoder;
System.Drawing.Imaging.EncoderParameter myEncoderParameter;
System.Drawing.Imaging.EncoderParameters myEncoderParameters;
myImageCodecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[0];
myEncoder = System.Drawing.Imaging.Encoder.Quality;
myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 100L); // 0-100
myEncoderParameters.Param[0] = myEncoderParameter;
bt1.Save(context.Server.MapPath(save_file), myImageCodecInfo, myEncoderParameters); //保存
myEncoderParameter.Dispose();
myEncoderParameters.Dispose();
}
else
{
//把缩略图保存到指定的虚拟路径
newimage.Save(context.Server.MapPath(save_file));
}
//释放image对象占用的资源
image.Dispose();
//释放newimage对象的资源
newimage.Dispose();
//context.Response.End();
}
}
}
调用
DrawImg di=new DrawImg();
string file="1777155026.jpg";
string new_file="s_1777155026.jpg";
di.cut_it=false;
di.Set_ThumbnailImage(100,100,file,new_file);