【问题标题】:Convert from binary data to an image control in ASP.NET在 ASP.NET 中从二进制数据转换为图像控件
【发布时间】:2011-11-15 12:00:21
【问题描述】:

我的数据库中有图像的二进制数据,我想在 ASP.NET 的图像控件中显示它。如何?如果不行,请另想办法将其保存到数据库中,并在图像控件中显示。

【问题讨论】:

标签: c# asp.net image binary-data


【解决方案1】:

像这样创建一个常规的 HTML img 元素:

<img runat="server" id="image" />

在code behind 中这样做:

image.src = "data:image/png;base64," + Convert.ToBase64String(imageBytes);

其中 imageBytes 是 byte[]。

你已经完成了。将显示图像。

【讨论】:

  • 这是迄今为止显示二进制图像最简单的方法。但我发现这种方法只适用于 jpg 图像。我用 png 图像试过这个,但没有用。
  • 该方法适用于 jpg 和 png,只要浏览器支持。可能是您的浏览器不支持它,或者它们的实现有问题。
  • 你能解释一下data:image/png;base64吗?
  • 你是对的,它是 IE 的问题,它在 chrome 中工作得很好。知道如何让它在 IE 中工作吗?
【解决方案2】:

图像很可能以字节数组的形式存储在数据库中。如果是这样,那么你可以使用这个:

public static System.Drawing.Image ByteArrayToImage(byte[] bArray)
{
    if (bArray == null)
        return null;

    System.Drawing.Image newImage;

    try
    {
        using (MemoryStream ms = new MemoryStream(bArray, 0, bArray.Length))
        {
            ms.Write(bArray, 0, bArray.Length);
            newImage = System.Drawing.Image.FromStream(ms, true);
        }
    }
    catch (Exception ex)
    {
        newImage = null;

        //Log an error here
    }

    return newImage;
}

【讨论】:

    【解决方案3】:
    public Byte[] Ret_image(Int32 id)
    {
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "select * from tbimage where imageid=@id";
        cmd.Connection = con;
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        Byte[] ar = (Byte[])(dr[1]);
        dr.Close();
        cmd.Dispose();
        return ar;
    }
    

    【讨论】:

      【解决方案4】:
      protected void Button2_Click(object sender, EventArgs e)
      {
          Byte[] ar = Ret_image(Convert.ToInt32(TextBox2.Text));
          String st = Server.MapPath("abc.jpg");
          FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
          fs.Write(ar, 0, ar.Length);
          fs.Close();
          Image1.ImageUrl = "abc.jpg";           
      }
      

      使用此事件用于按钮单击以检索图像并在此处调用Ret_Image 方法。

      【讨论】:

        【解决方案5】:

        在通用处理程序 (.ashx) 中:

        public class ImageHandler : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                if(!string.IsNullOrEmpty(context.Request.QueryString["ImageId"]))
                {
                   try
                   {
                        string ImageId = context.Request.QueryString["ImageId"].ToString(); 
                        ImageDataModel idm = new ImageDataModel();
                        byte[] ImageData = idm.getImageData(ImageId);
                        context.Response.ContentType = "image/JPEG";
                        context.Response.OutputStream.Write(ImageData, 0, ImageData.Length); 
                    }
                    catch(Exception ex){}
                }
            }
        
        }
        

        【讨论】:

          【解决方案6】:
          SqlConnection con = new SqlConnection();
          string _path;
          Using SYstem.IO;
          Using System.Data.SQLClient;
          
          //convert Image to binary and save in DB
          
          private void button1_Click(object sender, EventArgs e)
          {
              if (openFileDialog1.ShowDialog() == DialogResult.OK)
              {
                  _path = openFileDialog1.FileName;
                  InsertInSQL(_path);
              }
          }
          
          private void InsertInSQL(string _path)
          {
              con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
              string strQ = "insert into dbo.PicTBL(Pic)values(@p)";
              SqlCommand command = new SqlCommand(strQ,con);
              command.Parameters.AddWithValue("@p",ImageToBinary(_path));
              con.Open();
              command.ExecuteNonQuery();
              con.Close();
          }      
          
          public static byte[] ImageToBinary(string _path)
          {
              FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
              byte[] b = new byte[fS.Length];
              fS.Read(b, 0, (int)fS.Length);
              fS.Close();
              return b;
          }
          
          //Convert Binary to imge and save in a folder
          private void button1_Click_1(object sender, EventArgs e)
          {
              DataTable dt = Rimage();
              foreach (DataRow row in dt.Rows)
              {
                  byte[] b = (byte[])row["Pic"];
                  Image img = BinaryToImage(b);
                  img.Save("D:\\NewFolder\\" + row["ID"].ToString() + ".jpg");
              }
          }
          
          private Image BinaryToImage(byte[] b)
          {
              if (b == null) 
                  return null;
          
              MemoryStream memStream = new MemoryStream();
              memStream.Write(b, 0, b.Length);
          
              return Image.FromStream(memStream);
          }
          
          private DataTable Rimage()
          {
              con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
              SqlCommand cmd = new SqlCommand();
              cmd.CommandText = "select * from dbo.PicTBL";
              cmd.Connection = con;
              SqlDataAdapter adp = new SqlDataAdapter(cmd);
              DataTable dt = new DataTable();
              con.Open();
              adp.Fill(dt);
          
              return dt;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-22
            • 1970-01-01
            • 2013-02-10
            • 2011-05-29
            相关资源
            最近更新 更多