简体   繁体   English

如何显示以HTML格式从数据库返回的SQL Server filestream .jpg图像

[英]How do I present a SQL Server filestream .jpg image returned from the database in HTML

I am trying to retrieve jpeg files stored in SQL Server and present these in html using img src="filepath" but my C# code is returning the actual image, not a URL path to the image and this just displays a tiny image box with an x in it. 我正在尝试检索存储在SQL Server中的jpeg文件,并使用img src =“ filepath”将这些文件呈现为html,但是我的C#代码返回的是实际图像,而不是图像的URL路径,这只会显示一个带有x在里面。
How can I display the image directly as an image variable. 如何直接将图像显示为图像变量。 Here is the HTML page with Razor C#: 这是带有Razor C#的HTML页面:

@{ 
int iFileID = 8;
string sPhotoDesc = "";
Image iPhotoImage = null;
}
<form>

<fieldset>
    <legend>FileInput</legend>
    <input type="file" id="fileinput" />
    <input type='button' id='btnLoad' value='Load' onclick="@{iPhotoImage = 
         PhotoLibraryApp.PhotoData.SelectPhoto(iFileID, out sPhotoDesc); }">
    <div id="editor"></div>
</fieldset>

<img src="@iPhotoImage" width="500" height="377">

Here is the relevant C# code in a separate file called PhotoData.cs: 以下是名为PhotoData.cs的单独文件中的相关C#代码:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Drawing;
using System.IO;
using System.Transactions;


namespace PhotoLibraryApp
{
    public class PhotoData
    {
        private const string ConnStr =
          "Data Source=.;Integrated Security=True;Initial                                   
                               Catalog=PhotoLibrary;";

     public static Image SelectPhoto(int photoId, out string desc)
      {
        const string SelectTSql = @"
        SELECT
        Description,
        Photo.PathName(),
        GET_FILESTREAM_TRANSACTION_CONTEXT()
      FROM PhotoAlbum
      WHERE PhotoId = @PhotoId";

        Image photo;
        string serverPath;
        byte[] serverTxn;

        using (TransactionScope ts = new TransactionScope())
        {
            using (SqlConnection conn = new SqlConnection(ConnStr))
            {
                conn.Open();

                using (SqlCommand cmd = new SqlCommand(SelectTSql, conn))
                {
                    cmd.Parameters.Add("@PhotoId", SqlDbType.Int).Value = photoId;

                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        rdr.Read();
                        desc = rdr.GetSqlString(0).Value;
                        serverPath = rdr.GetSqlString(1).Value;
                        serverTxn = rdr.GetSqlBinary(2).Value;
                        rdr.Close();
                    }
                }
                photo = LoadPhotoImage(serverPath, serverTxn);
            }

            ts.Complete();
        }

        return photo;
    }

    private static Image LoadPhotoImage(string filePath, byte[] txnToken)
    {
        Image photo;

        using (SqlFileStream sfs =
          new SqlFileStream(filePath, txnToken, FileAccess.Read))
        {
            photo = Image.FromStream(sfs);
            sfs.Close();
        }

        return photo;
      }

  }
}

After trying to find an answer for 3 days, the following worked. 尝试寻找答案3天后,以下方法起作用。 Summary, once the iPhotoImage is returned from the database SQLFilestream code, this was then converted to a byte array using TurnImageToByteArray and then the imgBytes bytes were converted to string imgString which displayed the image in HTML. 总结,一旦iPhotoImage从数据库SQLFilestream代码返回,然后使用TurnImageToByteArray将其转换为字节数组,然后将imgBytes字节转换为字符串imgString,以HTML形式显示图像。 Here are the additional pieces of code: 以下是其他代码:

@{
//Get the file ID you want to display
int iFileID = 8;
string sPhotoDesc = "";
Image iPhotoImage = null;

iPhotoImage = PhotoLibraryApp.PhotoData.SelectPhoto(iFileID, out 
sPhotoDesc);

byte[] imgBytes = 
PhotoLibraryApp.PhotoData.TurnImageToByteArray(iPhotoImage);
string imgString = Convert.ToBase64String(imgBytes);

}

I added the following method to my PhotoData class: 我在PhotoData类中添加了以下方法:

  public static byte[] TurnImageToByteArray(Image img)
    {
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return ms.ToArray();
    }

The following is the html to display the image: 以下是显示图像的html:

 <img id="JpegImage" alt="Photo Alternative" src="data:image/jpeg;base64, @imgString">

After more effort, I found that I could not save to Memory stream for JPEG images. 经过更多的努力,我发现无法将JPEG图像保存到内存流中。 This gave the ubiquitous General GDI error. 这产生了普遍存在的通用GDI错误。 The JPEG files had to be converted to bitmp images first using the following code before I could get them to display: 必须先使用以下代码将JPEG文件转换为bitmp图像,然后才能显示它们:

(var ms = new MemoryStream())
{
    Bitmap bmp = new Bitmap(imageToConvert);
    bmp.Save(ms, format);
    return ms.ToArray();
}

Another note: The JPEG files come back from SQL Filestream as an image type of Bitmap, this was what clued me in to try this along with the entry by @Amir Atasin here: A generic error occurred in GDI+, JPEG Image to MemoryStream 另一个注意事项:JPEG文件从SQL Filestream作为位图的图像类型返回,这就是我试图与@Amir Atasin的条目一起尝试的原因: GDI +中发生了一般性错误,JPEG图像到MemoryStream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM