[英]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.