在 MVC ASP.NET 中显示运行时生成的图像:ashx 与 ImageResult
我引用 ashx 文件来显示运行时生成的图像:
<img alt="" style="height: 200px; width: 450px;"
id="Img1" src="<%= Url.Content ("~/Helpers/GetImage.ashx?side=Front") %>" />
下面是创建图像的代码。但我担心这不是正确的方法;我应该使用返回 ImageResult 的控制器吗?
if (!string.IsNullOrEmpty(context.Request.Params["side"]))
{
string ImageType = string.Empty;
if (context.Request.Params["side"].Equals("Front"))
{
ImageType="FrontJpegBase64";
}
else
{
ImageType = "BackJpegBase64";
}
Log.Info(context.Session["FrontBase64"].ToString());
byte[] imageByteArray = System.Convert.FromBase64String(context.Session[ImageType].ToString());
System.IO.MemoryStream imageMemoryStream = new System.IO.MemoryStream(imageByteArray);
try
{
using (System.Drawing.Image img = System.Drawing.Image.FromStream(imageMemoryStream))
{
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch (System.Exception ex)
{
Log.Error(ex, ": ConvertBytesToImage {0} ");
}
finally
{
imageMemoryStream.Close();
context.Response.Flush();
}
}
I am referencing an ashx file to show an image which is generated at runtime:
<img alt="" style="height: 200px; width: 450px;"
id="Img1" src="<%= Url.Content ("~/Helpers/GetImage.ashx?side=Front") %>" />
Below is the code that creates the image. But I'm concerned that this is not the right approach; should I instead use a controller that returns an ImageResult?
if (!string.IsNullOrEmpty(context.Request.Params["side"]))
{
string ImageType = string.Empty;
if (context.Request.Params["side"].Equals("Front"))
{
ImageType="FrontJpegBase64";
}
else
{
ImageType = "BackJpegBase64";
}
Log.Info(context.Session["FrontBase64"].ToString());
byte[] imageByteArray = System.Convert.FromBase64String(context.Session[ImageType].ToString());
System.IO.MemoryStream imageMemoryStream = new System.IO.MemoryStream(imageByteArray);
try
{
using (System.Drawing.Image img = System.Drawing.Image.FromStream(imageMemoryStream))
{
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch (System.Exception ex)
{
Log.Error(ex, ": ConvertBytesToImage {0} ");
}
finally
{
imageMemoryStream.Close();
context.Response.Flush();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ashx 比使用控制器操作快 7.23 倍。
ashx is 7.23 times faster than using controller actions.
我认为通过 ashx 处理它是一个很好的方法。我在我的一些项目中使用过它,效果非常好!
I think handling it through ashx is a good approach. I have used it in some of my projects and it worked great!