[英]How to set image from code behind?
我有以下aspx代码
<asp:Image ID="pbScannedImage" runat="server" />
我在C#代码后面的代码是
System.Drawing.Image image;
image = System.Drawing.Image.FromStream(new MemoryStream(dDSImageViewerDTO.ROI));
pbScannedImage.Visible = true;
pbScannedImage.ImageUrl = "";
// This is available but I don't want to write file to the disk and
// assign directly to the image box something like
pbScannedImage.Image = image;
//i know this is not possible so any other work around would be great help
因此,基本上我想将图像分配给图像控件而不将其写入其他任何位置。 是否可能,如果没有,是否有任何解决方法?
您可以将数据库映像逻辑分离为通用处理程序(ASHX),然后将处理程序用作映像的src,例如
img.src=GetImage.ashx?id=1;
您需要创建GetImage.ashx并适当处理您的ID(或您使用的任何对象)。 然后,您可以简单地写回该页面。
实现此目的的一种方法,特别是如果您要确保图像永远不会被缓存(这在动态加载的图像中很常见)是将图像数据作为CSS背景图像数据添加到诸如div之类的元素中,其方法如下:
“ background-image:url(data:image / gif; base64,” + ImageToBase64String(Image)+“)”
public string ImageToBase64String(Image image)
{
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, ImageFormat.Png);
return Convert.ToBase64String(stream.ToArray());
}
}
pbScannedImage.Src = "ImageHandler.ashx";
处理程序代码必须类似于:
名称
System.Drawing.Image dbImage =
System.Drawing.Image.FromFile("file path");
System.Drawing.Image thumbnailImage =
dbImage.GetThumbnailImage(80, 80, null, new System.IntPtr());
thumbnailImage.Save(mstream, dbImage.RawFormat);
Byte[] thumbnailByteArray = new Byte[mstream.Length];
mstream.Position = 0;
mstream.Read(thumbnailByteArray, 0, Convert.ToInt32(mstream.Length));
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(thumbnailByteArray);
解决了盖米的答案,您还可以像这样从后面的代码中分配img.Src。
pbScannedImage.Src = "data:image/png;base64," + ImageToBase64String(Image);
怎么说@Sain Pradeep,您可以创建服务(ashx或contoller方法,如果您使用mvc)来返回图像流,并将其与html标签<img>
(asp:Image被包装在<img>
)一起使用。 使用ashx处理程序查看显示图像中的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.