我正在尝试使用ImageResizer,这是一个非常好的图像裁剪器,当我直接在这样的图像上使用它时:
<img src="myimage.jpg?height=300" />
但是当我尝试使用ashx处理程序写出图像时,我遇到了一些问题。这是我的代码:
ImageHandler.ashx
string filePath = (HttpContext.Current.Request.PhysicalApplicationPath + context.Session["currentdirectory"]);
string file = context.Request.QueryString["name"];
MemoryStream ms = new MemoryStream();
ImageBuilder.Current.Build(new ImageJob(filePath + "/" + file, ms, new Instructions("height=300"), false, true));
context.Response.Write(ms.ToArray());
context.Response.ContentType = "image/jpeg";
context.Response.AddHeader(
"Content-Disposition",
"inline; filename=" + file);
似乎在使用上面的代码时,图像被破坏,或者正如mozilla firefox所说:图像'myimage.jpg'无法显示,因为它包含错误。
所以我猜它得到的字节数组显然是错误的?
我是否向Response.Write
发送了错误的类型,或者我只是以错误的方式使用ImageBuilder
?
或者在这里可以解决我的问题是什么?
编辑: 顺便说一下把它写入文件而不是内存流是有效的,所以在尝试通过处理程序编写它时我必须做错了吗?
var to = HttpContext.Current.Request.PhysicalApplicationPath + "/" + file;
ImageBuilder.Current.Build(new ImageJob(filePath + "/" + file, to, new Instructions("height=300")));
答案 0 :(得分:0)
这对我有用:
var filePath = HttpContext.Current.Server.MapPath("~/img");
var file = context.Request.QueryString["name"];
using(var ms = new MemoryStream())
{
ImageBuilder.Current.Build( new ImageJob( filePath + "/" + file, ms, new Instructions( "height=300" ), false, true ) );
context.Response.ContentType = "image/jpeg";
context.Response.AddHeader( "Content-Disposition", "inline; filename=" + file );
ms.WriteTo(context.Response.OutputStream);
}
或只是使用:
context.Response.BinaryWrite(ms.ToArray());
这也有效
答案 1 :(得分:-1)
确实
ImageBuilder.Current.Build(...)
在一个单独的线程中运行?如果是的话, 那么这可能是问题所在,你在任务完成之前就向流中写了一些东西。
可能有回调或同步方法来运行图像缩放器。