Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c# - How can I display an image from SQL Server using ASP.NET?

Here is my class (product.cs) where is the method to insert the image:

public static void InsertProductIMG(byte[] image, string contentType) 
{
   string cs = "Data Source=(local);Initial Catalog=myApp;Integrated Security=True";
   string comandoSql = "INSERT INTO [myApp].[dbo].[product] (image, ContentType) VALUES (@image, @contentType)";

   using (SqlConnection conn = new SqlConnection(cs))
   {
       conn.Open();

       using (SqlTransaction trans = conn.BeginTransaction())
       {
           SqlCommand cmd = new SqlCommand(comandoSql, conn, trans);
           SqlParameter[] parms = new SqlParameter[2];
           parms[0] = new SqlParameter("@image", image);
           parms[1] = new SqlParameter("@contentType", contentType);
           foreach (SqlParameter p in parms)
           {
              cmd.Parameters.Add(p);
           }

           cmd.ExecuteNonQuery();
           trans.Commit();
       }
    }
}

Here is the code behind of the apsx page where I call the method above:

byte[] imageBytes = new byte[fupld.PostedFile.InputStream.Length];
product.InsertProductIMG(imageBytes, "image/jpeg");//product is the class where the method is

Now I'd like to know how can I display this image?

Would I have to read the byte[] from sql (SELECT), convert to string and so convert to byte[]? And after do that convert to bitmap (System.Drawing). But how I show this bitmap in a aspx page?

I've no idea how to do it. Please help!! :]

Thanks

Obs.: In SQL Server, the column image is of type varbinary(MAX).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create a web page that returns the image. You would select the bytes from the database (as you have already code written to insert, I think you know how to select). Once you have the bytes, you need to set the mime type and write the bytes to the response stream.

var bytesFromDatabase = getImageFromDatabase();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(bytesFromDatabase);

Edit:

Just use a img tag with the cource tet to the aforementioned aspx web page. Eg:

<img src="http://www.example.com/image.aspx?id=1" alt="image" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...