当前位置: 编程技术>.net/c#/asp.net
c#生成高清缩略图的二个示例分享
来源: 互联网 发布时间:2014-10-29
本文导语: 代码如下:/// /// 为图片生成缩略图 /// /// 原图片的路径 /// 缩略图宽 /// 缩略图高 /// public System.Drawing.Image GetThumbnail(System.Drawing.Image image, int width, intheight) { Bitmap bmp = newBitmap(width, height); //从Bitmap创建一个System.Drawing...
代码如下:
///
/// 为图片生成缩略图
///
/// 原图片的路径
/// 缩略图宽
/// 缩略图高
///
public System.Drawing.Image GetThumbnail(System.Drawing.Image image, int width, intheight)
{
Bitmap bmp = newBitmap(width, height);
//从Bitmap创建一个System.Drawing.Graphics
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
//设置
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//下面这个也设成高质量
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//下面这个设成High
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
//把原始图像绘制成上面所设置宽高的缩小图
System.Drawing.Rectangle rectDestination = newSystem.Drawing.Rectangle(0, 0, width, height);
gr.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
returnbmp;
}
调用方法
代码如下:
HttpPostedFile file = photoFile.PostedFile;
if(!file.ContentType.Contains("image"))
{
return"照片格式不合法";
}
stringext = Path.GetExtension(file.FileName).ToLower();
if (ext != ".jpg" && ext != ".gif" && ext != ".png"&& ext != ".jpeg")
{
return"请您上传jpg、gif、png图片";
}
if(file.ContentLength > 5 * 1024 * 1024)
{
return"请您上传512字节内的图片";
}
stringnewName = Guid.NewGuid().ToString();
stringtempPath = "upload/";
stringimg = tempPath + newName + ext;
stringfilePath = Server.MapPath(img);
if(!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
using(System.Drawing.Image originalImage = System.Drawing.Image.FromStream(file.InputStream))
{
GetThumbnail(originalImage, 504, 374).Save(filePath);
示例2
代码如下:
public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height)
{
//获取原始图片
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;
//原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
int bg_x = 0;
int bg_y = 0;
int bg_w = towidth;
int bg_h = toheight;
//倍数变量
double multiple = 0;
//获取宽长的或是高长与缩略图的倍数
if (originalImage.Width >= originalImage.Height)
multiple = (double)originalImage.Width / (double)width;
else
multiple = (double)originalImage.Height / (double)height;
//上传的图片的宽和高小等于缩略图
if (ow