using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AirWheel.Cycling.Domain;
using AirWheel.Cycling.Common;
using AirWheel.Cycling.Service.IService;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Configuration;
using System.Collections;
using AirWheel.Cycling.WebPage.Controllers;
namespace AirWheel.Cycling.WebPage.Areas.ComManage.Controllers
{
///
/// 文件上传控制器
/// add 作者: 季健国 QQ:181589805 by 2016-10-14
///
public class UploadController : BaseController
{
#region 声明容器
///
/// 文章管理
///
IUploadManage UploadManage { get; set; }
#endregion
#region 公共变量
#endregion
#region 基本视图
///
/// 加载首页
///
[UserAuthorizeAttribute(ModuleAlias = "Upload", OperaAction = "View")]
public ActionResult Index()
{
ViewBag.Search = base.keywords;
return View(BindList());
}
///
/// 加载详情
///
[UserAuthorizeAttribute(ModuleAlias = "Upload", OperaAction = "Detail")]
public ActionResult Detail(string id)
{
var entity = this.UploadManage.Get(p => p.ID == id) ?? new COM_UPLOAD();
return View(entity);
}
#endregion
#region 公共方法
///
/// 绑定列表数据
///
private PageInfo BindList()
{
var query = this.UploadManage.LoadAll(null);
if (!string.IsNullOrEmpty(keywords))
{
query = query.Where(p => p.UPOLDNAME.Contains(keywords));
}
//除管理员,其他人默认看自己的文件
if (!this.CurrentUser.IsAdmin)
{
var userid = CurrentUser.Id.ToString();
query = query.Where(p => p.FK_USERID == userid);
}
query = query.OrderByDescending(p => p.UPTIME);
return this.UploadManage.Query(query, base.page, base.pagesize);
}
#endregion
#region 私有方法
///
/// 返回上传目录相对路径
///
/// 上传文件名
private string GetUpLoadPath(bool isImg, string ext)
{
string path = ConfigurationManager.AppSettings["uppath"];
if (isImg && IsImage(ext))
{
path += "images/";
}
else
{
path += "files/";
}
#region 用户控制
//判读是否为超级管理员,超级管理员可查看所有的文件
if (!base.CurrentUser.IsAdmin)
{
path += base.CurrentUser.LogName + "/";
}
#endregion
path += DateTime.Now.ToString("yyyyMMdd") + "/";
return path;
}
///
/// 是否为图片文件
///
/// 文件扩展名,不含“.”
private bool IsImage(string _fileExt)
{
ArrayList al = new ArrayList();
al.Add("bmp");
al.Add("jpeg");
al.Add("jpg");
al.Add("gif");
al.Add("png");
if (al.Contains(_fileExt.ToLower()))
return true;
return false;
}
///
/// 是否需要打水印
///
/// 文件扩展名,不含“.”
private bool IsWaterMark(string _fileExt)
{
//判断是否开启水印
if (ConfigurationManager.AppSettings["watermarktype"].ToString() != "0")
{
//判断是否可以打水印的图片类型
ArrayList al = new ArrayList();
al.Add("bmp");
al.Add("jpeg");
al.Add("jpg");
al.Add("png");
if (al.Contains(_fileExt.ToLower()))
{
return true;
}
}
return false;
}
///
/// 检查是否为合法的上传文件
///
private bool CheckFileExt(string _fileExt)
{
//检查危险文件
string[] excExt = { "asp", "aspx", "php", "jsp", "htm", "html" };
for (int i = 0; i < excExt.Length; i++)
{
if (excExt[i].ToLower() == _fileExt.ToLower())
{
return false;
}
}
//检查合法文件
string[] allowExt = ConfigurationManager.AppSettings["attachextension"].ToString().Split(',');
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i].ToLower() == _fileExt.ToLower())
{
return true;
}
}
return false;
}
///
/// 检查文件大小是否合法
///
/// 文件扩展名,不含“.”
/// 文件大小(B)
private bool CheckFileSize(string _fileExt, int _fileSize)
{
//判断是否为图片文件
if (IsImage(_fileExt))
{
if (_fileSize > int.Parse(ConfigurationManager.AppSettings["attachimgsize"].ToString()) * 1024)
return false;
}
else
{
if (_fileSize > int.Parse(ConfigurationManager.AppSettings["attachfilesize"].ToString()) * 1024)
return false;
}
return true;
}
///
/// 是否真实,入侵验证
///
/// 文件post
/// 新文件路径+文件名
///
private bool CheckFileTrue(HttpPostedFileBase _fileBinary, string newfilePath)
{
Stream fs = _fileBinary.InputStream;
BinaryReader br = new BinaryReader(fs);
byte but;
string str = "";
try
{
but = br.ReadByte();
str = but.ToString();
but = br.ReadByte();
str += but.ToString();
}
catch
{
return false;
}
/*文件扩展名说明
* 4946/104116 txt
* 7173 gif
* 255216 jpg
* 13780 png
* 6677 bmp
* 239187 txt,aspx,asp,sql
* 208207 xls.doc.ppt
* 6063 xml
* 6033 htm,html
* 4742 js
* 8075 xlsx,zip,pptx,mmap,zip
* 8297 rar
* 01 accdb,mdb
* 7790 exe,dll
* 5666 psd
* 255254 rdp
* 10056 bt种子
* 64101 bat
* 4059 sgf
* 3780 pdf
*/
bool bl = false;
string[] binary = { "4946", "104116", "7173", "255216", "13780", "6677", "239187", "208207", "6063", "6033", "4742", "8075", "8297", "01", "5666", "255254", "10056" };
for (int i = 0; i < binary.Length; i++)
{
if (binary[i].ToLower() == str.ToLower())
{
bl = true;
}
}
if (bl)
{
_fileBinary.SaveAs(newfilePath);
}
br.Close();
fs.Close();
return bl;
}
///
/// 文件上传方法
///
/// 文件流
/// 是否生成缩略图
/// 上传后文件信息
private JsonHelper FileSaveAs(HttpPostedFileBase postedFile, bool isThumbnail, bool isWater, bool isImg)
{
var jsons = new JsonHelper { Status = "n" };
try
{
string fileExt = Utils.GetFileExt(postedFile.FileName); //文件扩展名,不含“.”
int fileSize = postedFile.ContentLength; //获得文件大小,以字节为单位
string fileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名
string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名
string upLoadPath = GetUpLoadPath(isImg, fileExt); //上传目录相对路径
string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径
string newFilePath = upLoadPath + newFileName; //上传后的路径
string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名
//检查文件扩展名是否合法
if (!CheckFileExt(fileExt))
{
jsons.Msg = "不允许上传" + fileExt + "类型的文件!";
return jsons;
}
//检查文件大小是否合法
if (!CheckFileSize(fileExt, fileSize))
{
jsons.Msg = "文件超过限制的大小啦!";
return jsons;
}
//检查上传的物理路径是否存在,不存在则创建
if (!Directory.Exists(fullUpLoadPath))
{
Directory.CreateDirectory(fullUpLoadPath);
}
//检查文件是否真实合法
//if (!CheckFileTrue(postedFile, fullUpLoadPath + newFileName))
//{
// jsons.Msg = "不允许上传不可识别的文件!";
// return jsons;
//}
postedFile.SaveAs(fullUpLoadPath + newFileName);
string thumbnail = string.Empty;
//如果是图片,检查是否需要生成缩略图,是则生成
if (IsImage(fileExt) && isThumbnail && ConfigurationManager.AppSettings["thumbnailwidth"].ToString() != "0" && ConfigurationManager.AppSettings["thumbnailheight"].ToString() != "0")
{
Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newThumbnailFileName,
int.Parse(ConfigurationManager.AppSettings["thumbnailwidth"]), int.Parse(ConfigurationManager.AppSettings["thumbnailheight"]), "Cut");
thumbnail = upLoadPath + newThumbnailFileName;
}
//如果是图片,检查是否需要打水印
if (IsWaterMark(fileExt) && isWater)
{
switch (ConfigurationManager.AppSettings["watermarktype"].ToString())
{
case "1":
WaterMark.AddImageSignText(newFilePath, newFilePath,
ConfigurationManager.AppSettings["watermarktext"], int.Parse(ConfigurationManager.AppSettings["watermarkposition"]),
int.Parse(ConfigurationManager.AppSettings["watermarkimgquality"]), ConfigurationManager.AppSettings["watermarkfont"], int.Parse(ConfigurationManager.AppSettings["watermarkfontsize"]));
break;
case "2":
WaterMark.AddImageSignPic(newFilePath, newFilePath,
ConfigurationManager.AppSettings["watermarkpic"], int.Parse(ConfigurationManager.AppSettings["watermarkposition"]),
int.Parse(ConfigurationManager.AppSettings["watermarkimgquality"]), int.Parse(ConfigurationManager.AppSettings["watermarktransparency"]));
break;
}
}
string unit = string.Empty;
//处理完毕,返回JOSN格式的文件信息
jsons.Data = "{\"oldname\": \"" + fileName + "\","; //原始名称
jsons.Data += " \"newname\":\"" + newFileName + "\","; //新名称
jsons.Data += " \"path\": \"" + newFilePath + "\", "; //路径
jsons.Data += " \"thumbpath\":\"" + thumbnail + "\","; //缩略图
jsons.Data += " \"size\": \"" + fileSize + "\","; //大小
jsons.Data += "\"ext\":\"" + fileExt + "\"}";//后缀名
jsons.Status = "y";
return jsons;
}
catch
{
jsons.Msg = "上传过程中发生意外错误!";
return jsons;
}
}
#endregion
#region 其他调用
///
/// 上传主调用器
///
public ActionResult FileMain()
{
return View();
}
///
/// 图片预览视图
///
public ActionResult Show()
{
return View();
}
///
/// 通过路径获取文件
///
///
public ActionResult GetFileData()
{
string path = Request.Form["path"];
var jsonM = new JsonHelper() { Status = "y", Msg = "success" };
try
{
jsonM.Data = Utils.DataTableToList(FileHelper.GetFileTable(Server.MapPath(path))).OrderByDescending(p => p.time).ToList();
}
catch (Exception ex)
{
jsonM.Status = "err";
jsonM.Msg = "上传过程中发生错误,消息:" + ex.Message;
}
return Content(JsonConverter.Serialize(jsonM, true));
}
///
/// 单个文件上传
///
[HttpPost]
public ActionResult SignUpFile()
{
var jsonM = new JsonHelper() { Status = "n", Msg = "success" };
try
{
HttpPostedFileBase upfile = Request.Files["fileUp"]; //取得上传文件
var isImg = Request.QueryString["isImg"];
string delpath = Request.QueryString["delpath"];
if (upfile == null)
{
jsonM.Msg = "请选择要上传文件!";
return Json(jsonM);
}
jsonM = FileSaveAs(upfile, false, false, (isImg.ToLower() == "true" ? true : false));
#region 移除原始文件
if (jsonM.Status == "y" && !string.IsNullOrEmpty(delpath))
{
if (System.IO.File.Exists(Utils.GetMapPath(delpath)))
{
System.IO.File.Delete(Utils.GetMapPath(delpath));
}
}
#endregion
if (jsonM.Status == "y")
{
#region 记录上传数据
string unit = string.Empty;
var jsonValue = JsonConverter.ConvertJson(jsonM.Data.ToString());
var entity = new COM_UPLOAD()
{
ID = Guid.NewGuid().ToString(),
FK_USERID = this.CurrentUser.Id.ToString(),
UPOPEATOR = this.CurrentUser.Name,
UPTIME = DateTime.Now,
UPOLDNAME = jsonValue.oldname,
UPNEWNAME = jsonValue.newname,
UPFILESIZE = FileHelper.GetDiyFileSize(long.Parse(jsonValue.size), out unit),
UPFILEUNIT = unit,
UPFILEPATH = jsonValue.path,
UPFILESUFFIX = jsonValue.ext,
UPFILETHUMBNAIL = jsonValue.thumbpath,
UPFILEIP = Utils.GetIP(),
UPFILEURL = "http://" + Request.Url.AbsoluteUri.Replace("http://", "").Substring(0, Request.Url.AbsoluteUri.Replace("http://", "").IndexOf('/'))
};
this.UploadManage.Save(entity);
#endregion
#region 返回文件信息
jsonM.Data = "{\"oldname\": \"" + jsonValue.oldname + "\","; //原始名称
jsonM.Data += " \"newname\":\"" + jsonValue.newname + "\","; //新名称
jsonM.Data += " \"path\": \"" + jsonValue.path + "\", "; //路径
jsonM.Data += " \"thumbpath\":\"" + jsonValue.thumbpath + "\","; //缩略图
jsonM.Data += " \"size\": \"" + jsonValue.size + "\","; //大小
jsonM.Data += " \"id\": \"" + entity.ID + "\","; //上传文件ID
jsonM.Data += " \"uptime\": \"" + entity.UPTIME + "\","; //上传时间
jsonM.Data += " \"operator\": \"" + entity.UPOPEATOR + "\","; //上传人
jsonM.Data += " \"unitsize\": \"" + entity.UPFILESIZE + unit + "\","; //带单位大小
jsonM.Data += "\"ext\":\"" + jsonValue.ext + "\"}";//后缀名
#endregion
}
}
catch (Exception ex)
{
jsonM.Msg = "上传过程中发生错误,消息:" + ex.Message;
jsonM.Status = "n";
}
return Json(jsonM);
}
///
/// 删除文件或文件夹
///
///
public ActionResult DeleteBy()
{
var jsonM = new JsonHelper() { Status = "y", Msg = "success" };
try
{
var path = Request.QueryString["path"];
var isFile = Request.QueryString["isfile"];
if (isFile == "0")
{
//删除文件夹
FileHelper.ClearDirectory(Server.MapPath(path));
}
else
{
//删除文件
FileHelper.DeleteFile(Server.MapPath(path));
}
}
catch (Exception ex)
{
jsonM.Status = "err";
jsonM.Msg = "删除过程中发生错误,消息:" + ex.Message;
}
return Json(jsonM);
}
#endregion
}
#region 自定义类
///
/// 文件模型
///
public class FileModel
{
public string name { get; set; }
public string ext { get; set; }
public string size { get; set; }
public DateTime time { get; set; }
}
///
/// 缩略图构造类
///
public class Thumbnail
{
private Image srcImage;
private string srcFileName;
///
/// 创建
///
/// 原始图片路径
public bool SetImage(string FileName)
{
srcFileName = Utils.GetMapPath(FileName);
try
{
srcImage = Image.FromFile(srcFileName);
}
catch
{
return false;
}
return true;
}
///
/// 回调
///
///
public bool ThumbnailCallback()
{
return false;
}
///
/// 生成缩略图,返回缩略图的Image对象
///
/// 缩略图宽度
/// 缩略图高度
/// 缩略图的Image对象
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;
}
///
/// 保存缩略图
///
///
///
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;
}
}
///
/// 生成缩略图并保存
///
/// 缩略图的宽度
/// 缩略图的高度
/// 保存的图像格式
/// 缩略图的Image对象
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
///
/// 保存图片
///
/// Image 对象
/// 保存路径
/// 指定格式的编解码参数
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();
}
///
/// 获取图像编码解码器的所有相关信息
///
/// 包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串
/// 返回图像编码解码器的所有相关信息
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType)
return ici;
}
return null;
}
///
/// 计算新尺寸
///
/// 原始宽度
/// 原始高度
/// 最大新宽度
/// 最大新高度
///
private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
{
//此次2012-02-05修改过=================
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);
}
///
/// 得到图片格式
///
/// 文件名称
///
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
///
/// 制作小正方形
///
/// 图片对象
/// 新地址
/// 长度或宽度
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();
}
}
///
/// 制作小正方形
///
/// 图片文件名
/// 新地址
/// 长度或宽度
public static void MakeSquareImage(string fileName, string newFileName, int newSize)
{
MakeSquareImage(Image.FromFile(fileName), newFileName, newSize);
}
///
/// 制作远程小正方形
///
/// 图片url
/// 新地址
/// 长度或宽度
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);
}
///
/// 制作缩略图
///
/// 图片对象
/// 新图路径
/// 最大宽度
/// 最大高度
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();
}
}
}
///
/// 制作缩略图
///
/// 文件名
/// 新图路径
/// 最大宽度
/// 最大高度
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 2012-2-19 新增生成图片缩略图方法
///
/// 生成缩略图
///
/// 源图路径(绝对路径)
/// 缩略图路径(绝对路径)
/// 缩略图宽度
/// 缩略图高度
/// 生成缩略图的方式
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 2012-10-30 新增图片裁剪方法
///
/// 裁剪图片并保存
///
/// 源图路径(绝对路径)
/// 缩略图路径(绝对路径)
/// 缩略图宽度
/// 缩略图高度
/// 裁剪宽度
/// 裁剪高度
/// X轴
/// Y轴
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, cropWidth), 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
///
/// 制作远程缩略图
///
/// 图片URL
/// 新图路径
/// 最大宽度
/// 最大高度
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);
}
///
/// 获取图片流
///
/// 图片URL
///
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;
}
}
}
///
/// 水印构造类
///
public class WaterMark
{
///
/// 图片水印
///
/// 服务器图片相对路径
/// 保存文件名
/// 水印文件相对路径
/// 图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下
/// 附加水印图片质量,0-100
/// 水印的透明度 1--10 10为不透明
public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
{
if (!File.Exists(Utils.GetMapPath(imgPath)))
return;
byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
filename = Utils.GetMapPath(filename);
if (watermarkFilename.StartsWith("/") == false)
watermarkFilename = "/" + watermarkFilename;
watermarkFilename = Utils.GetMapPath(watermarkFilename);
if (!File.Exists(watermarkFilename))
return;
Graphics g = Graphics.FromImage(img);
//设置高质量插值法
//g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
//g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
Image watermark = new Bitmap(watermarkFilename);
if (watermark.Height >= img.Height || watermark.Width >= img.Width)
return;
ImageAttributes imageAttributes = new ImageAttributes();
ColorMap colorMap = new ColorMap();
colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
ColorMap[] remapTable = { colorMap };
imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
float transparency = 0.5F;
if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
transparency = (watermarkTransparency / 10.0F);
float[][] colorMatrixElements = {
new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, transparency, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
int xpos = 0;
int ypos = 0;
switch (watermarkStatus)
{
case 1:
xpos = (int)(img.Width * (float).01);
ypos = (int)(img.Height * (float).01);
break;
case 2:
xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
ypos = (int)(img.Height * (float).01);
break;
case 3:
xpos = (int)((img.Width * (float).99) - (watermark.Width));
ypos = (int)(img.Height * (float).01);
break;
case 4:
xpos = (int)(img.Width * (float).01);
ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
break;
case 5:
xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
break;
case 6:
xpos = (int)((img.Width * (float).99) - (watermark.Width));
ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
break;
case 7:
xpos = (int)(img.Width * (float).01);
ypos = (int)((img.Height * (float).99) - watermark.Height);
break;
case 8:
xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
ypos = (int)((img.Height * (float).99) - watermark.Height);
break;
case 9:
xpos = (int)((img.Width * (float).99) - (watermark.Width));
ypos = (int)((img.Height * (float).99) - watermark.Height);
break;
}
g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo ici = null;
foreach (ImageCodecInfo codec in codecs)
{
if (codec.MimeType.IndexOf("jpeg") > -1)
ici = codec;
}
EncoderParameters encoderParams = new EncoderParameters();
long[] qualityParam = new long[1];
if (quality < 0 || quality > 100)
quality = 80;
qualityParam[0] = quality;
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
encoderParams.Param[0] = encoderParam;
if (ici != null)
img.Save(filename, ici, encoderParams);
else
img.Save(filename);
g.Dispose();
img.Dispose();
watermark.Dispose();
imageAttributes.Dispose();
}
///
/// 文字水印
///
/// 服务器图片相对路径
/// 保存文件名
/// 水印文字
/// 图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下
/// 附加水印图片质量,0-100
/// 字体
/// 字体大小
public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
{
byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
filename = Utils.GetMapPath(filename);
Graphics g = Graphics.FromImage(img);
Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
SizeF crSize;
crSize = g.MeasureString(watermarkText, drawFont);
float xpos = 0;
float ypos = 0;
switch (watermarkStatus)
{
case 1:
xpos = (float)img.Width * (float).01;
ypos = (float)img.Height * (float).01;
break;
case 2:
xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
ypos = (float)img.Height * (float).01;
break;
case 3:
xpos = ((float)img.Width * (float).99) - crSize.Width;
ypos = (float)img.Height * (float).01;
break;
case 4:
xpos = (float)img.Width * (float).01;
ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
break;
case 5:
xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
break;
case 6:
xpos = ((float)img.Width * (float).99) - crSize.Width;
ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
break;
case 7:
xpos = (float)img.Width * (float).01;
ypos = ((float)img.Height * (float).99) - crSize.Height;
break;
case 8:
xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
ypos = ((float)img.Height * (float).99) - crSize.Height;
break;
case 9:
xpos = ((float)img.Width * (float).99) - crSize.Width;
ypos = ((float)img.Height * (float).99) - crSize.Height;
break;
}
g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo ici = null;
foreach (ImageCodecInfo codec in codecs)
{
if (codec.MimeType.IndexOf("jpeg") > -1)
ici = codec;
}
EncoderParameters encoderParams = new EncoderParameters();
long[] qualityParam = new long[1];
if (quality < 0 || quality > 100)
quality = 80;
qualityParam[0] = quality;
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
encoderParams.Param[0] = encoderParam;
if (ici != null)
img.Save(filename, ici, encoderParams);
else
img.Save(filename);
g.Dispose();
img.Dispose();
}
}
#endregion
}