如何在c#中的<img/>标签中写入图像

时间:2015-05-22 13:35:39

标签: c# asp.net-mvc

我现在正在使用字符串连接我的HTML来自我的数据库的HTML DB中还有一些图像存储路径和字节... 现在我想在html <img>标签中显示我的图像然后我将其写在doc文件

这是我的代码:

&#13;
&#13;
if (ds.Tables[4].Rows.Count > 0)
{

    DataTable Dt_4 = ds.Tables[4];

    foreach (DataRow item in Dt_4.Rows)
    {
        QuestionName += "<br style='page-break-before: always'> <br style='page-break-before: always'>";
        QuestionName += "<b><span style='text-decoration:underline'>Question :  </span>" + Dt_4.Rows[0]["Q_Num"].ToString() + "</b>";
                                
        QuestionName += "<b><span style='padding-left:20px;'>Marks :  </span>(" + item["Marks"].ToString() + ")</b>";
        QuestionName += item["QuestionName"].ToString();

        string imagePath = item["ImagePath"].ToString();
                               
        QuestionName += " <div><img src='" + imagePath + "' height='350' width='450'> </div> ";
                             
    }                      
}
&#13;
&#13;
&#13;

当我在服务器上运行时图像显示正确但是当我从本地计算机访问服务器时它没有显示 任何帮助???

1 个答案:

答案 0 :(得分:4)

您可以将图像嵌入Base64编码字符串,如下所示:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAM0AAAD
 NCAMAAAAsYgRbAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5c
 cllPAAAABJQTFRF3NSmzMewPxIG//ncJEJsldTou1jHgAAAARBJREFUeNrs2EEK
 gCAQBVDLuv+V20dE....." alt="beastie.png">

    string MakeImageSrcData(string filename)
    {
        byte[] filebytes = System.IO.File.ReadAllBytes(filename);
        return "data:image/png;base64," +Convert.ToBase64String(filebytes, Base64FormattingOptions.None);
    }

<img src="<%=MakeImageSrcData("c:\path\to\my.png") %>" />

https://devio.wordpress.com/2011/01/13/embedding-images-in-html-using-c/ http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/