从SQL Server VarBinary中读取图像(最大值) [英] Read Image from SQL Server VarBinary(Max)

查看:99
本文介绍了从SQL Server VarBinary中读取图像(最大值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SQL Server数据库.我已经在其中存储了一个图像,它是varbinary(max).我通过以下方式插入了图像:

I have a SQL Server Database. I have stored an image in there which is a varbinary(max). I inserted the image the following way :

string consString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
            SqlConnection con = new SqlConnection(consString);
            con.Open();

            String filePath = fuImage.PostedFile.FileName;
            String naam = Path.GetFileName(filePath);
            String extension = Path.GetExtension(naam);

            Stream stream = fuImage.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(stream);
            Byte[] imgByte = br.ReadBytes((Int32)stream.Length);


            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "spAddImage";
            cmd.Parameters.AddWithValue("@FOTO", imgByte);
            cmd.Parameters.AddWithValue("@ARTIEST", ddlArtiest.SelectedValue);
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
            con.Close();

图像现在在数据库中看起来像这样: 它存储为varbinary.

The image now looks like this in the database : It is stored as a varbinary.

http://puu.sh/ikF83/6a03b52520.png <-数据库

现在,我想在已插入的asp.net页面上显示我的图像.

Now I want to display my image on my asp.net page that I have inserted.

但是我不知道如何实现这一目标.

But I have no idea how I can achieve this.

推荐答案

您可以使用SqlDataReader查看结果并获取所需的内容

You could use SqlDataReader to go over the results and get back what you need

var reader = cmd.ExecuteReader();
while (reader.Read())
{
  byte[] myImage = (byte[])reader["MyImageColumn"];
}

这是从我的头上来的,因此请根据需要进行调整.但这应该给您基本的想法.

This is from top of my head so make your adjustments as required. But it should give you the basic idea.

此外,强烈建议使用using块,因为它可以确保正确放置对象.

Furthermore, It's strongly recommended to use the using block as it ensures the object is disposed correctly.

因此您可以将代码更改为

So you could change your code to

using(var connection = new SqlConnection(connectionString))
{
  //Your command 
  connection.Open();

  //Datareader here

}//Object disposed here

的引用SqlDataReader

使用块的引用

这篇关于从SQL Server VarBinary中读取图像(最大值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆