PictureWebHandler
using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using EW.EWorkpal.Core.Common.MongoProvider.MongoGridFSRepository.Models;
using EW.EWorkpal.Core.System;
using EW.EWorkpal.Services.FileManagerService.ImageProvider; namespace EW.EWorkpal.Modules.Picture
{
public class PictureWebHandler : ServiceBase, IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
#region 客户端缓存
int clientCacheTime; //客户端缓存时间(秒)
string clientCacheSecond = GetAppSetting("ClientCacheSecond", true);
if (!int.TryParse(clientCacheSecond, out clientCacheTime))
clientCacheTime = ;
string clearHeadImage = request.Headers["Clear-HeadImage"];
if (!string.IsNullOrEmpty(clearHeadImage))
{
ClearClientCaching(context.Response);
return;
}
string headerModified = request.Headers["If-Modified-Since"];
if (headerModified != null)
{
long nowTicks = DateTime.Now.Ticks;
long modifiedTick = DateTime.Parse(request.Headers["If-Modified-Since"]).Ticks;
long ticks = nowTicks - modifiedTick;
if (TimeSpan.FromTicks(ticks).Seconds < clientCacheTime)
{
response.StatusCode = ;
// 这种方式会产生“此操作要求使用 IIS 集成管线模式。 ”的异常
//Response.Headers.Add("Content-Encoding", "gzip");
// Response.Headers.Add 和 Response.AddHeader 但是在MSDN中明确写出,这些都是为了兼容ASP,在.NET 3.5要求使用下面这种方式。
//这种方式不会出现异常
response.AppendHeader("Content-Encoding", "gzip");
response.StatusDescription = "Not Madified";
response.End();
return;
}
}
#endregion
string regex = GetAppSetting("UrlRegex");
string sourceRegex = GetAppSetting("SourceUrlRegex");
string headRegex = GetAppSetting("HeadImageUrlRegex");
string comLogoRegex = GetAppSetting("ComLogoUrlRegex");
string url = request.Url.AbsoluteUri;
int regexIndex;
if (Regex.IsMatch(url, headRegex, RegexOptions.IgnoreCase))
regexIndex = ;
else if (Regex.IsMatch(url, comLogoRegex, RegexOptions.IgnoreCase))
regexIndex = ;
else if (Regex.IsMatch(url, regex, RegexOptions.IgnoreCase))
regexIndex = ;
else if (Regex.IsMatch(url, sourceRegex, RegexOptions.IgnoreCase))
regexIndex = ;
else
regexIndex = ;
if (regexIndex == )
{
Error404(response);
return;
}
#region 用户头像
if (regexIndex == )
{
var regResult = Regex.Match(url, @"\d+/\d+").Value;
var str = regResult.Split('/');
if (str.Length < )
{
Error404(response);
return;
}
int id, size;
if (!int.TryParse(str[], out id))
{
Error404(response);
return;
}
if (!int.TryParse(str[], out size))
{
Error404(response);
return;
}
if (size == )
{
size = ;
}
else if (size == )
{
size = ;
}
else
{
size = ;
}
var srcPicBytes = GetService<IImageService>().GetHeadImage(id);
if (srcPicBytes != null)
{
Stream stream = GetHighHeadImage(srcPicBytes, size);
long dataToRead = stream.Length;
byte[] bytes = ((MemoryStream)stream).GetBuffer();
response.Buffer = true;
response.ContentType = "image/jpeg";
while (dataToRead > )
{
if (response.IsClientConnected)
{
int length = bytes.Length;
byte[] buffer = bytes;
response.OutputStream.Write(buffer, , length);
response.Flush();
dataToRead = dataToRead - length;
}
else
{
dataToRead = -;
}
}
SetClientCaching(response, DateTime.Now, clientCacheTime);
}
else
{
//if (requesthost != picturehost)//盗链,返回提示图片
////{
//// context.Response.WriteFile("/Img/linknotice/ImageForbiden.jpg");
////}
context.Response.ClearContent();
context.Response.WriteFile("/img/headimg/noavatar_" + size + "_" + size + ".jpg");
context.Response.ContentType = "image/jpeg";
context.Response.End();
return; }
// context.Response.ClearContent();
// context.Response.ContentType = "image/jpeg";
context.Response.End();
return;
} #endregion #region 企业Logo
if (regexIndex == )
{
var regResult = Regex.Match(url, @"ent/\d+").Value;
var str = regResult.Split('/');
if (str.Length < )
{
Error404(response);
return;
}
int size;
if (!int.TryParse(str[], out size))
{
Error404(response);
return;
}
if (size == )
{
size = ;
}
else if (size == )
{
size = ;
}
else
{
size = ;
}
string fileName = regexIndex == ? Regex.Match(url, regex, RegexOptions.IgnoreCase).Groups[].Value : Regex.Match(url, sourceRegex, RegexOptions.IgnoreCase).Groups[].Value;
MongoFileInfo options;
var srcPicBytes = GetService<IImageService>().Get(fileName, out options);
if (srcPicBytes != null)
{
Stream stream = GetHighHeadImage(srcPicBytes, size);
long dataToRead = stream.Length;
byte[] bytes = ((MemoryStream)stream).GetBuffer();
response.Buffer = true;
response.ContentType = "image/jpeg";
while (dataToRead > )
{
if (response.IsClientConnected)
{
int length = bytes.Length;
byte[] buffer = bytes;
response.OutputStream.Write(buffer, , length);
response.Flush();
dataToRead = dataToRead - length;
}
else
{
dataToRead = -;
}
}
SetClientCaching(response, DateTime.Now, clientCacheTime);
}
else
{
context.Response.ClearContent();
context.Response.WriteFile(string.Format("/img/comlogo/{0}x{0}.jpg",size));
context.Response.ContentType = "image/jpeg";
context.Response.End();
return; }
// context.Response.ClearContent();
// context.Response.ContentType = "image/jpeg";
context.Response.End();
return;
}
#endregion #region 读取原图 if (regexIndex == || regexIndex == )
{
string fileName = regexIndex == ? Regex.Match(url, regex, RegexOptions.IgnoreCase).Groups[].Value : Regex.Match(url, sourceRegex, RegexOptions.IgnoreCase).Groups[].Value;
MongoFileInfo options;
var srcPicBytes = GetService<IImageService>().Get(fileName, out options);
if (srcPicBytes == null || srcPicBytes.Length <= )
{
Error404(response);
return;
}
var srcPicStream = new MemoryStream(srcPicBytes);
Image srcImage = Image.FromStream(srcPicStream);
Image destImage = null;
if (regexIndex == )
{
int destWidth = int.Parse(Regex.Match(url, regex, RegexOptions.IgnoreCase).Groups[].Value);
int destHeight = int.Parse(Regex.Match(url, regex, RegexOptions.IgnoreCase).Groups[].Value);
string zoomType = Regex.Match(url, regex, RegexOptions.IgnoreCase).Groups[].Value;
bool zoomCut = zoomType.ToUpper() == "-C";
bool zoomFit = zoomType.ToUpper() == "-F";
//缩略
destImage = ZoomPic.Zoom(srcImage,
new ZoomParam
{
Width = destWidth,
Height = destHeight,
Type =
zoomCut
? EnumZoomType.Cut
: zoomFit ? EnumZoomType.Fit : EnumZoomType.Cut
});
}
else
{
//返回原图
destImage = srcImage;
}
#region 输出
Stream stream = new MemoryStream();
try
{
if (destImage != null) destImage.Save(stream, ImageFormat.Jpeg);
long dataToRead = stream.Length;
byte[] bytes = ((MemoryStream)stream).GetBuffer();
SetClientCaching(response, DateTime.Now, clientCacheTime);
response.Buffer = true;
response.ContentType = "image/jpeg";
while (dataToRead > )
{
if (response.IsClientConnected)
{
int length = bytes.Length;
byte[] buffer = bytes;
response.OutputStream.Write(buffer, , length);
response.Flush();
dataToRead = dataToRead - length;
}
else
{
dataToRead = -;
}
}
}
catch (Exception e)
{
ClearClientCaching(response);
throw new Exception(e.Message);
}
finally
{
srcImage.Dispose();
srcPicStream.Dispose();
if (destImage != null) destImage.Dispose();
stream.Dispose();
}
#endregion
} #endregion } #region private methods private static string GetAppSetting(string key, bool allowNull = false)
{
if (ConfigurationManager.AppSettings[key] == null)
{
if (allowNull)
return "";
throw new ConfigurationErrorsException(string.Format("找不到appSettings配置,配置项{0}", key));
}
return ConfigurationManager.AppSettings[key];
} private void SetClientCaching(HttpResponse response, DateTime lastModified, int clientCacheTime)
{
response.ContentType = "image/jpeg";
//将ETag Http标头设置为制定字符串
response.Cache.SetETag(lastModified.Ticks.ToString(CultureInfo.InvariantCulture));
//将Last_Modified Http标头设置为提供的System.DateTime值
response.Cache.SetLastModified(lastModified);
//将Cache-Control 标头设置为System.Web.HttpCacheability值之一
response.Cache.SetCacheability(HttpCacheability.Public);
//基于制定的时间跨度设置Cache-Control: max-age HTTP标头
response.Cache.SetMaxAge(new TimeSpan(, , , clientCacheTime));
//将缓存过期从绝对时间设置为可调时间
response.Cache.SetSlidingExpiration(true);
} private void ClearClientCaching(HttpResponse response)
{
response.Cache.SetExpires(DateTime.Now);
} private MemoryStream GetHeadImage(Byte[] file, int size)
{
size = size > ? : size;
MemoryStream stream = new MemoryStream(file);
Bitmap bmp = new Bitmap(Image.FromStream(stream));
Image image = bmp.GetThumbnailImage(size, size, null, IntPtr.Zero);
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);
return ms;
} private MemoryStream GetHighHeadImage(Byte[] file, int size)
{
MemoryStream ms = new MemoryStream();
Image originalImage = Image.FromStream(new MemoryStream(file));
//新建一个bmp图片
Image bitmap = new Bitmap(size, size);
//新建一个画板
Graphics g = Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(, , size, size), new Rectangle(, , originalImage.Width, originalImage.Height), GraphicsUnit.Pixel);
try
{
//以jpg格式保存缩略图
bitmap.Save(ms, ImageFormat.Png);
}
catch (Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
return ms;
} #endregion /// <summary>
/// 返回404
/// </summary>
private static void Error404(HttpResponse response)
{
response.StatusCode = ;
response.Flush();
response.End();
} public bool IsReusable { get { return false; } }
}
}
PictureWebHandler的更多相关文章
随机推荐
- Python学习(3)变量类型
目录 变量赋值 多个变量赋值 标准数据类型 Python数字 Python字符串 Python列表 Python元组 Python元字典 Python数据类型转换 type数据类型查看 变量赋值 Py ...
- hibernate的主键生成策略
一共是13种,其中包括native native: 对于 oracle 采用 Sequence 方式,对于MySQL 和 SQL Server 采用identity(自增主键生成机制),native就 ...
- svn提交代码的原则
[1]先更新在提交 [2]多提交 [3]不要提交不能通过编译的代码 [4]每次提交必须书写明晰的标注 [5]提交时注意不要提交本地自动生成的文件 [6]不要提交自己不明白的代码 [7]慎用锁定功能
- iOS之Photos:访问某个相册通过collectionView显示
文中相关知识点较多,只记载重点思路,相关部分都有对应注释说明,部分还需要优化,只是工作学习的一种思路. @import AVFoundation; @import Photos; 导入框架 - ( ...
- IE浏览器GET传参后台乱码
ie里面 get传递的字符串 为 gb2312 ,后台用的是utf-8类型 所以用 POST传递字符串到后端 否则进行js参数转码 encodeURI(""); 后端解码
- Java 抓取 thread dump (Full Thread Stack Trace) 方法汇总
顾名思义,表示一个时间点上,显示进程里面每一个线程的 stack trace,以及线程之间关联,比如等待 常用来定位一些 不响应,CPU 很高,内存使用很高问题 汇总表格如下 工具 操作系统 Java ...
- xmpp怎么让群主踢人?
不知道其他语言版的xmpp,framework是怎样的,就OC版提供的xmpp框架来说,它只提供了邀请其他用户进群的API: - (void)inviteUser:(XMPPJID *)jid wit ...
- Django数据库设置
设置数据库,创建您的第一个模型,得到一个简单介绍 Django的自动生成管理网站. 数据库设置 现在,打开 mysite / settings.py . 这是一个普通的Python模块 模块级变量代表 ...
- selenium+python笔记2
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @desc: 操作浏览器 """ fro ...
- http协议分析工具【转】
转自:http://www.cnblogs.com/klguang/p/4624333.html