常用工具类9-上传缩略图类

public class Thumbnail
{
private Image srcImage;
private string srcFileName;

/// <summary>
/// 创建
/// </summary>
/// <param name="FileName">原始图片路径</param>
public bool SetImage(string FileName)
{
srcFileName = Utils.GetMapPath(FileName);
try
{
srcImage = Image.FromFile(srcFileName);
}
catch
{
return false;
}
return true;

}

/// <summary>
/// 回调
/// </summary>
/// <returns></returns>
public bool ThumbnailCallback()
{
return false;
}

/// <summary>
/// 生成缩略图,返回缩略图的Image对象
/// </summary>
/// <param name="Width">缩略图宽度</param>
/// <param name="Height">缩略图高度</param>
/// <returns>缩略图的Image对象</returns>
public Image GetImage(int Width,int Height)
{
Image img;
Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
img = srcImage.GetThumbnailImage(Width,Height,callb, IntPtr.Zero);
return img;
}

/// <summary>
/// 保存缩略图
/// </summary>
/// <param name="Width"></param>
/// <param name="Height"></param>
public void SaveThumbnailImage(int Width,int Height)
{
switch(Path.GetExtension(srcFileName).ToLower())
{
case ".png":
SaveImage(Width, Height, ImageFormat.Png);
break;
case ".gif":
SaveImage(Width, Height, ImageFormat.Gif);
break;
default:
SaveImage(Width, Height, ImageFormat.Jpeg);
break;
}
}

/// <summary>
/// 生成缩略图并保存
/// </summary>
/// <param name="Width">缩略图的宽度</param>
/// <param name="Height">缩略图的高度</param>
/// <param name="imgformat">保存的图像格式</param>
/// <returns>缩略图的Image对象</returns>
public void SaveImage(int Width,int Height, ImageFormat imgformat)
{
if (imgformat != ImageFormat.Gif && (srcImage.Width > Width) || (srcImage.Height > Height))
{
Image img;
Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
srcImage.Dispose();
img.Save(srcFileName, imgformat);
img.Dispose();
}
}

#region Helper

/// <summary>
/// 保存图片
/// </summary>
/// <param name="image">Image 对象</param>
/// <param name="savePath">保存路径</param>
/// <param name="ici">指定格式的编解码参数</param>
private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
{
//设置 原图片 对象的 EncoderParameters 对象
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long) 100));
image.Save(savePath, ici, parameters);
parameters.Dispose();
}

/// <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="width">原始宽度</param>
/// <param name="height">原始高度</param>
/// <param name="maxWidth">最大新宽度</param>
/// <param name="maxHeight">最大新高度</param>
/// <returns></returns>
private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
{

if (maxWidth <= 0)
maxWidth = width;
if (maxHeight <= 0)
maxHeight = height;
//以上2012-02-05修改过=================
decimal MAX_WIDTH = (decimal)maxWidth;
decimal MAX_HEIGHT = (decimal)maxHeight;
decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT;

int newWidth, newHeight;
decimal originalWidth = (decimal)width;
decimal originalHeight = (decimal)height;

if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
{
decimal factor;
// determine the largest factor
if (originalWidth / originalHeight > ASPECT_RATIO)
{
factor = originalWidth / MAX_WIDTH;
newWidth = Convert.ToInt32(originalWidth / factor);
newHeight = Convert.ToInt32(originalHeight / factor);
}
else
{
factor = originalHeight / MAX_HEIGHT;
newWidth = Convert.ToInt32(originalWidth / factor);
newHeight = Convert.ToInt32(originalHeight / factor);
}
}
else
{
newWidth = width;
newHeight = height;
}
return new Size(newWidth,newHeight);
}

/// <summary>
/// 得到图片格式
/// </summary>
/// <param name="name">文件名称</param>
/// <returns></returns>
public static ImageFormat GetFormat(string name)
{
string ext = name.Substring(name.LastIndexOf(".") + 1);
switch (ext.ToLower())
{
case "jpg":
case "jpeg":
return ImageFormat.Jpeg;
case "bmp":
return ImageFormat.Bmp;
case "png":
return ImageFormat.Png;
case "gif":
return ImageFormat.Gif;
default:
return ImageFormat.Jpeg;
}
}
#endregion

/// <summary>
/// 制作小正方形
/// </summary>
/// <param name="image">图片对象</param>
/// <param name="newFileName">新地址</param>
/// <param name="newSize">长度或宽度</param>
public static void MakeSquareImage(Image image, string newFileName, int newSize)
{
int i = 0;
int width = image.Width;
int height = image.Height;
if (width > height)
i = height;
else
i = width;

Bitmap b = new Bitmap(newSize, newSize);

try
{
Graphics g = Graphics.FromImage(b);
//设置高质量插值法
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
//清除整个绘图面并以透明背景色填充
g.Clear(Color.Transparent);
if (width < height)
g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle(0, (height-width)/2, width, width), GraphicsUnit.Pixel);
else
g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle((width-height)/2, 0, height, height), GraphicsUnit.Pixel);

SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
}
finally
{
image.Dispose();
b.Dispose();
}
}

/// <summary>
/// 制作小正方形
/// </summary>
/// <param name="fileName">图片文件名</param>
/// <param name="newFileName">新地址</param>
/// <param name="newSize">长度或宽度</param>
public static void MakeSquareImage(string fileName, string newFileName, int newSize)
{
MakeSquareImage(Image.FromFile(fileName), newFileName, newSize);
}

/// <summary>
/// 制作远程小正方形
/// </summary>
/// <param name="url">图片url</param>
/// <param name="newFileName">新地址</param>
/// <param name="newSize">长度或宽度</param>
public static void MakeRemoteSquareImage(string url, string newFileName, int newSize)
{
Stream stream = GetRemoteImage(url);
if (stream == null)
return;
Image original = Image.FromStream(stream);
stream.Close();
MakeSquareImage(original, newFileName, newSize);
}

/// <summary>
/// 制作缩略图
/// </summary>
/// <param name="original">图片对象</param>
/// <param name="newFileName">新图路径</param>
/// <param name="maxWidth">最大宽度</param>
/// <param name="maxHeight">最大高度</param>
public static void MakeThumbnailImage(Image original, string newFileName, int maxWidth, int maxHeight)
{
Size _newSize = ResizeImage(original.Width,original.Height,maxWidth, maxHeight);

using (Image displayImage = new Bitmap(original, _newSize))
{
try
{
displayImage.Save(newFileName, original.RawFormat);
}
finally
{
original.Dispose();
}
}
}

/// <summary>
/// 制作缩略图
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="newFileName">新图路径</param>
/// <param name="maxWidth">最大宽度</param>
/// <param name="maxHeight">最大高度</param>
public static void MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight)
{
//2012-02-05修改过,支持替换
byte[] imageBytes = File.ReadAllBytes(fileName);
Image img = Image.FromStream(new System.IO.MemoryStream(imageBytes));
MakeThumbnailImage(img, newFileName, maxWidth, maxHeight);
//原文
//MakeThumbnailImage(Image.FromFile(fileName), newFileName, maxWidth, maxHeight);
}

#region  生成图片缩略图方法
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="fileName">源图路径(绝对路径)</param>
/// <param name="newFileName">缩略图路径(绝对路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
public static void MakeThumbnailImage(string fileName, string newFileName, int width, int height, string mode)
{
Image originalImage = Image.FromFile(fileName);
int towidth = width;
int toheight = height;

int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;

switch (mode)
{
case "HW"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}

//新建一个bmp图片
Bitmap b = new Bitmap(towidth, toheight);
try
{
//新建一个画板
Graphics g = Graphics.FromImage(b);
//设置高质量插值法
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);

SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
b.Dispose();
}
}
#endregion

#region  图片裁剪方法
/// <summary>
/// 裁剪图片并保存
/// </summary>
/// <param name="fileName">源图路径(绝对路径)</param>
/// <param name="newFileName">缩略图路径(绝对路径)</param>
/// <param name="maxWidth">缩略图宽度</param>
/// <param name="maxHeight">缩略图高度</param>
/// <param name="cropWidth">裁剪宽度</param>
/// <param name="cropHeight">裁剪高度</param>
/// <param name="X">X轴</param>
/// <param name="Y">Y轴</param>
public static bool MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y)
{
byte[] imageBytes = File.ReadAllBytes(fileName);
Image originalImage = Image.FromStream(new System.IO.MemoryStream(imageBytes));
Bitmap b = new Bitmap(cropWidth, cropHeight);
try
{
using (Graphics g = Graphics.FromImage(b))
{
//设置高质量插值法
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(0, 0, cropWidth, cropHeight), X, Y, cropWidth, cropHeight, GraphicsUnit.Pixel);
Image displayImage = new Bitmap(b, maxWidth, maxHeight);
SaveImage(displayImage, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
return true;
}
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
b.Dispose();
}
}
#endregion

/// <summary>
/// 制作远程缩略图
/// </summary>
/// <param name="url">图片URL</param>
/// <param name="newFileName">新图路径</param>
/// <param name="maxWidth">最大宽度</param>
/// <param name="maxHeight">最大高度</param>
public static void MakeRemoteThumbnailImage(string url, string newFileName, int maxWidth, int maxHeight)
{
Stream stream = GetRemoteImage(url);
if(stream == null)
return;
Image original = Image.FromStream(stream);
stream.Close();
MakeThumbnailImage(original, newFileName, maxWidth, maxHeight);
}

/// <summary>
/// 获取图片流
/// </summary>
/// <param name="url">图片URL</param>
/// <returns></returns>
private static Stream GetRemoteImage(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
request.ContentLength = 0;
request.Timeout = 20000;
HttpWebResponse response = null;

try
{
response = (HttpWebResponse)request.GetResponse();
return response.GetResponseStream();
}
catch
{
return null;
}
}
}

时间: 2024-10-06 00:40:44

常用工具类9-上传缩略图类的相关文章

php 图片操作类,支持生成缩略图,添加水印,上传缩略图

<?php class Image {     //类开始     public $originimage = ""; //源图片文件地址     public $imageext = ""; //源图片格式     public $thumbimage = ""; //缩略图文件存放地址     public $thumb_maxwidth = 1440; //缩略图最大宽度     public $thumb_maxheight = 9

django-自定义文件上传存储类

文件储存API:https://yiyibooks.cn/xx/django_182/ref/files/storage.html 编写自定义存储系统:https://yiyibooks.cn/xx/django_182/howto/custom-file-storage.html 定义一个自定义的储存类步骤 1.你的自定义储存类必须是django.core.files.storage.Storage的子类 2.Django必须能够不带任何参数来实例化你的储存类.这意味着任何设置都应该从djan

文件上传帮助类

using System; using System.Collections.Generic; using System.Text; using System.Web.UI.WebControls; using System.IO; namespace AIMSCommon { /// <summary> /// 文件上传帮助类 /// </summary> public class UploadHelper { /// <summary> /// 文件上传 /// &

PHP 上传文件类

<?php /** * * @name upload.class.php * 上传文件类 * @author Peter * @createtime 2014-11-20 10:30:29 * */ class upload{ public $max_size; //上传file大小 public $allow_types; //上传文件类型 public $file_name; //文件名 public $errmsg; //错误提示 public $uploaded; //后的文件名 pub

Uploader 文件上传器类

概述 客户端完全基于JavaScript的 浏览器文件上传器,不需要任何浏览器插件,但需要和jQuery框架协同工作,支持超大文件上传,其算法是将一个超大文件切片成N个数据块依次提交给服务 端处理,由服务端存储断点信息实现断点续传的功能:支持文件拖拽上传,直接将文件拖拽到页面元素上方即可自动上传(默认元素是body):服务端采用asp.net 4.0程序开发,包含有处理程序,提供程序和视图控件,当然也可以用java或者php实现服务端程序. 浏览器兼容:IE10+.火狐.谷歌.Opera.win

phpcms v9升级后台无法上传缩略图的原因分析

phpcms V9 是目前国内使用人数最多的一款开源免费的CMS系统,正是由于他的免费性,开源性,以及其自身的功能性比较强大,所以倍受许多站长朋友们的亲来,以及许多的公司的喜欢.phpcms也为了完善程序漏洞,官方人员会经常性的发布一些程序补丁,让用户使用.防止一些特殊群体,通过程序的漏洞去攻击别人的网站.不过这次更新了phpcms v9之后,发现网站后台上传缩略图的时候,会出现无法上传的现象,浏览器提示undefined错误,经过一方面的测试,发现这个错误,只有一些火狐核心的浏览器才会出现,I

使用工具实现文件上传

开发步骤: 先给大家介绍了要用到的两个类: (1)DIskFileItemFactory对象:用于设置缓存大小和缓存目录 (2)ServletFileUpload对象:来解析文件 1]导两个jar包 commons-fileupload-1.2.2.jar   右键Build Path  -->  add path commons-io-2.0.1.jar 右键Build Path  -->  add path 在E盘下新建一个文件夹为TestData,在文件夹中新建两个文件夹:FileTem

Dedecms本地上传缩略图无法自动添加水印的解决方法

客户遇到一个问题,DEDECMS(V5.7)后台添加文档时,本地上传缩略图无法自动添加水印(系统设置里的图片水印设置没有问题),找了半天,终于找到了解决方法,留个记号: 打开dede/archives_do.php 找到第111行 $upfile = AdminUpload('litpic', 'imagelit', 0, false ); 改成 $upfile = AdminUpload('litpic', 'imagelit', 0, true ); 然后打开include/helpers/

php 文件上传缩略图路径分析类

<?php //文件上传时分析路径信息 //author:songzhenghe 2014-1-24 //version 0.1 class path_ana {     private $data_root;     private $web_root;     private $http_domain;     private $file;     private $r;          public function __construct(){         //从配置文件中读取  

[C#]工具类—FTP上传下载

public class FtpHelper { /// <summary> /// ftp方式上传 /// </summary> public static int UploadFtp(string filePath, string filename, string ftpServerIP, string ftpUserID, string ftpPassword) { FileInfo fileInf = new FileInfo(filePath + "\\&quo