使用asp.net中的数据库将图像转换为二进制和二进制到图像 [英] to Convert image to binary and binary to image using database in asp.net

查看:92
本文介绍了使用asp.net中的数据库将图像转换为二进制和二进制到图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好......



我想将图像转换为二进制并将其保存在数据库中...并将二进制数据恢复到图像和上传该图片..



我的代码如...

Hello......

I want to convert image to binary and save it in database...and also get back binary data to image and upload that image..

I have code like..

 private System.Drawing.Image BinaryToImage(byte[] b)
    {
        if (b == null)
            return null;
        MemoryStream memstream = new MemoryStream();
        memstream.Write(b, 0, b.Length);
        return System.Drawing.Image.FromStream(memstream);
    }

//for view
GridViewRow gridViewRow = CategoryGridView.SelectedRow;
            SqlDataReader dr = null;

            try
            {
                string qry = "select * from Category where cat_id =" + gridViewRow.Cells[1].Text;
                cmd = new SqlCommand(qry, cn);
                dr=cmd.ExecuteReader();
                if (dr.Read())
                {
                    lblcat_id.Text = dr[0].ToString();
                    txt_categorynm.Text = dr[1].ToString();
                    byte[] b = (byte[])dr[2];
                    System.Drawing.Image img = BinaryToImage(b);
                    string filepath = "User_image" + "//" + lblcat_id.Text + ".png";
                    FileStream fs = File.Create(filepath);
                    fs.Write(b, 0, b.Length);
                    fs.Flush();
                    fs.Close();
                    Image1.ImageUrl = "~/" + filepath;
                }
                else { }

            }
            catch
            {

            }



plz,给mi解决方案..

谢谢你..


plz,give mi solution..
thank u..

推荐答案

我认为您的 BinaryToImage 方法存在问题。在向其写入字节后,您需要将流的位置移动到流的开头:

I think there is a problem in your BinaryToImage method. After writing the bytes to it, you need to move the position of the stream to the beginning of the stream:
private System.Drawing.Image BinaryToImage(byte[] b)
   {
       if (b == null)
           return null;
       MemoryStream memstream = new MemoryStream();
       memstream.Write(b, 0, b.Length);
       memstream.Seek(0, SeekOrigin.Begin);
       return System.Drawing.Image.FromStream(memstream);
   }



如果这不起作用,那么图片可能会错误地存储在您的数据库中:

为什么我会得到一个参数无效。我从数据库中读取图像时出现异常? [ ^ ]


这篇关于使用asp.net中的数据库将图像转换为二进制和二进制到图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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