将图像文件保存到sql Server并将字节数组转换为图像

发布于 2024-12-27 01:26:05 字数 5386 浏览 0 评论 0原文

我将图像存储在数据库中,并希望将它们从字节数组转换为图像。将对象转换为字节数组没有问题,但在尝试从字节数组转换为图像时出现“参数无效”错误。我传递给方法的对象来自数据集行。

存储过程

USE [----------------]
GO
/****** Object:  StoredProcedure [dbo].[usp_imageloader_add_test]    Script Date: 01/16/2012    09:19:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER   procedure [dbo].[usp_imageloader_add_test]
@p_Image Image
as 

INSERT into Test_Images VALUES(@p_Image)

上传文件控件 /将图像文件转换为字节数组并保存数据到数据库

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ctrlUpload.PostedFile != null)
        {
            if (ctrlUpload.PostedFile.ContentLength > 0)
            {
                // Get Posted File
                HttpPostedFile objHttpPostedFile = ctrlUpload.PostedFile;

                // Find its length and convert it to byte array
                int ContentLength = objHttpPostedFile.ContentLength;

                // Create Byte Array
                byte[] bytImg = new byte[ContentLength];

                // Read Uploaded file in Byte Array
                objHttpPostedFile.InputStream.Read(bytImg, 0, ContentLength);

                using (SqlConnection dbConnection = new SqlConnection(app_settings.sql_conn_string_db))
                {
                    try
                    {
                        string sql = "usp_imageloader_add_test";
                        SqlCommand cmd = new SqlCommand(sql, dbConnection);
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@p_Image", bytImg).SqlDbType = SqlDbType.Binary;
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();
                        cmd.Connection.Close();
                    }


                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                    }
                }
            }
        }
    }

调用objToImg方法的Table方法

protected void Page_Load(object sender, EventArgs e)
    {
        generateTable(false);
    }


private Table generateTable(bool flag)
    {
        Table tb = BuildList(GetData(), flag);
        if (imgloadercms != null)
        {

            PlaceHolder ph = new PlaceHolder();
            StringBuilder sb = new StringBuilder();
            ph.Controls.Add(new LiteralControl(sb.ToString()));
        }
        imgloadercms.Controls.Add(tb);
        return tb;
    }


protected Table BuildList(DataTable tb, bool flag)
    {   
        Table tblImageLibrary = new Table();
        tblImageLibrary.BorderStyle = BorderStyle.Solid;
        tblImageLibrary.BorderWidth = Unit.Pixel(8);

        if (tb.Rows.Count > 0)
        {
            try
            {
                if (!flag)
                {

                    tblImageLibrary.BorderColor = Color.Black;
                    tblImageLibrary.BorderWidth = Unit.Pixel(1);
                    TableRow tr = new TableRow();  // Table row for header of table
                    tr.BackColor = Color.LightBlue;

                    TableCell c1 = new TableCell();
                    TableCell c2 = new TableCell();


                    c1.Controls.Add(new LiteralControl("Image Id"));
                    tr.Cells.Add(c1);
                    c2.Controls.Add(new LiteralControl("Image"));
                    tr.Cells.Add(c2);

                    tblImageLibrary.Rows.Add(tr);
                }

                int i = 0;

                foreach (DataRow r in tb.Rows) // Create new row foreach row in table
                {
                    TableRow tr = new TableRow();
                    if (i % 2 == 0)
                    {
                        tr.BackColor = Color.LightYellow;
                    }
                    // Build cells
                    TableCell c1 = new TableCell();
                    TableCell c2 = new TableCell();
                    c2.Width = 300;

                    c1.Controls.Add(new LiteralControl(r["Image_Id"].ToString()));
                    tr.Cells.Add(c1);

                    // Call method to serialize obj to byte array
                    //System.Drawing.Image dbImg = 
                    ObjToImg(r["Image_File"]);

               }
            catch (Exception ex)
            {
                ex.ToString();
            }
            if (!flag)
            {

            }
        }
        return tblImageLibrary;
    }

返回图像< /strong>

  private System.Drawing.Image ObjToImg(object obj)
    {
        //byte[] byteArray = null;

        if (obj == null)
            return null;
        else
        {

            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                bf.Serialize(ms, obj); //now in Memory Stream
                ms.ToArray(); // Array object
                ms.Seek(0, SeekOrigin.Begin);

                //return (System.Drawing.Image)bf.Deserialize(ms);

                System.Drawing.Image myImage = (System.Drawing.Image)bf.Deserialize(ms);

                return myImage;
            }

每当我尝试将内存流对象添加到图像对象构造函数时,我都会收到“参数无效”的错误消息。也许我在将字节数组插入数据库时​​犯了一个错误,因为我查看了其他代码,但它不工作是没有意义的。

I am storing images in a database and would like to convert them from byte array to image. I have no problem converting an object to byte array but I get an error of "Parameter is not valid" when trying to convert from byte array to image. The object I am passing to my method is from a dataset row.

Stored procedure

USE [----------------]
GO
/****** Object:  StoredProcedure [dbo].[usp_imageloader_add_test]    Script Date: 01/16/2012    09:19:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER   procedure [dbo].[usp_imageloader_add_test]
@p_Image Image
as 

INSERT into Test_Images VALUES(@p_Image)

Upload File control /convert Image file to byte array and save data to database

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ctrlUpload.PostedFile != null)
        {
            if (ctrlUpload.PostedFile.ContentLength > 0)
            {
                // Get Posted File
                HttpPostedFile objHttpPostedFile = ctrlUpload.PostedFile;

                // Find its length and convert it to byte array
                int ContentLength = objHttpPostedFile.ContentLength;

                // Create Byte Array
                byte[] bytImg = new byte[ContentLength];

                // Read Uploaded file in Byte Array
                objHttpPostedFile.InputStream.Read(bytImg, 0, ContentLength);

                using (SqlConnection dbConnection = new SqlConnection(app_settings.sql_conn_string_db))
                {
                    try
                    {
                        string sql = "usp_imageloader_add_test";
                        SqlCommand cmd = new SqlCommand(sql, dbConnection);
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@p_Image", bytImg).SqlDbType = SqlDbType.Binary;
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();
                        cmd.Connection.Close();
                    }


                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                    }
                }
            }
        }
    }

Table method which calls objToImg method

protected void Page_Load(object sender, EventArgs e)
    {
        generateTable(false);
    }


private Table generateTable(bool flag)
    {
        Table tb = BuildList(GetData(), flag);
        if (imgloadercms != null)
        {

            PlaceHolder ph = new PlaceHolder();
            StringBuilder sb = new StringBuilder();
            ph.Controls.Add(new LiteralControl(sb.ToString()));
        }
        imgloadercms.Controls.Add(tb);
        return tb;
    }


protected Table BuildList(DataTable tb, bool flag)
    {   
        Table tblImageLibrary = new Table();
        tblImageLibrary.BorderStyle = BorderStyle.Solid;
        tblImageLibrary.BorderWidth = Unit.Pixel(8);

        if (tb.Rows.Count > 0)
        {
            try
            {
                if (!flag)
                {

                    tblImageLibrary.BorderColor = Color.Black;
                    tblImageLibrary.BorderWidth = Unit.Pixel(1);
                    TableRow tr = new TableRow();  // Table row for header of table
                    tr.BackColor = Color.LightBlue;

                    TableCell c1 = new TableCell();
                    TableCell c2 = new TableCell();


                    c1.Controls.Add(new LiteralControl("Image Id"));
                    tr.Cells.Add(c1);
                    c2.Controls.Add(new LiteralControl("Image"));
                    tr.Cells.Add(c2);

                    tblImageLibrary.Rows.Add(tr);
                }

                int i = 0;

                foreach (DataRow r in tb.Rows) // Create new row foreach row in table
                {
                    TableRow tr = new TableRow();
                    if (i % 2 == 0)
                    {
                        tr.BackColor = Color.LightYellow;
                    }
                    // Build cells
                    TableCell c1 = new TableCell();
                    TableCell c2 = new TableCell();
                    c2.Width = 300;

                    c1.Controls.Add(new LiteralControl(r["Image_Id"].ToString()));
                    tr.Cells.Add(c1);

                    // Call method to serialize obj to byte array
                    //System.Drawing.Image dbImg = 
                    ObjToImg(r["Image_File"]);

               }
            catch (Exception ex)
            {
                ex.ToString();
            }
            if (!flag)
            {

            }
        }
        return tblImageLibrary;
    }

Return Image

  private System.Drawing.Image ObjToImg(object obj)
    {
        //byte[] byteArray = null;

        if (obj == null)
            return null;
        else
        {

            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                bf.Serialize(ms, obj); //now in Memory Stream
                ms.ToArray(); // Array object
                ms.Seek(0, SeekOrigin.Begin);

                //return (System.Drawing.Image)bf.Deserialize(ms);

                System.Drawing.Image myImage = (System.Drawing.Image)bf.Deserialize(ms);

                return myImage;
            }

Whenever I try to add the memory stream object to the image object constructor I get the error message of "Parameter is not valid". Maybe I made a mistake when insert the byte array into the database because I have looked at other code and it doesn't make sense how it's not working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

本宫微胖 2025-01-03 01:26:05

首先尝试使用 BinaryFormatter 从字节数组中反序列化对象!

尝试使用以下两种方法:

private System.Drawing.Image ObjToImg(byte[] obj)
    {
        if (obj == null)
            return null;
        else
        {
            BinaryFormatter bf = new BinaryFormatter();
            using(MemoryStream ms = new MemoryStream(obj))
            {
              return (System.Drawing.Image)bf.Deserialize(ms);
            }
        }
    }
private byte[] ImgToObj(System.Drawing.Image obj)
    {
        if (obj == null)
            return null;
        else
        {
            BinaryFormatter bf = new BinaryFormatter();
            using(MemoryStream ms = new MemoryStream())
            {
              bf.Serialize(ms, obj);
              return ms.ToArray();
            }
        }
    }

Try to deserialize the object first from byte array with your BinaryFormatter!

Try to use following two methods:

private System.Drawing.Image ObjToImg(byte[] obj)
    {
        if (obj == null)
            return null;
        else
        {
            BinaryFormatter bf = new BinaryFormatter();
            using(MemoryStream ms = new MemoryStream(obj))
            {
              return (System.Drawing.Image)bf.Deserialize(ms);
            }
        }
    }
private byte[] ImgToObj(System.Drawing.Image obj)
    {
        if (obj == null)
            return null;
        else
        {
            BinaryFormatter bf = new BinaryFormatter();
            using(MemoryStream ms = new MemoryStream())
            {
              bf.Serialize(ms, obj);
              return ms.ToArray();
            }
        }
    }
贵在坚持 2025-01-03 01:26:05

我最近不得不在 VB.NET 中做同样的事情。这是我的代码,通过 Telerik 的代码转换器运行。开始工作非常棘手,而且老实说仍然很痛苦。

要上传图像:

private bool uploadImage(ref Bitmap p)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = Configuration.ConfigurationManager.ConnectionStrings("ConnStringHere").ConnectionString;
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "INSERT INTO Table_Name (File2) VALUES (@File2)"; //I named the column File2 simply because "File" seemed to be a keyword in SQLServer
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;

    SqlParameter File1 = new SqlParameter("@File2", SqlDbType.Image);
    MemoryStream ms = new MemoryStream();

    using (Bitmap tempImage = new Bitmap(p))
    {
        tempImage.Save(ms, p.RawFormat);
    }

    byte[] data = ms.GetBuffer();
    if (!isValidImage(data)) //optional, will include code if requested.
    {
        return false;
    }
    File1.Value = data;
    cmd.Parameters.Add(File1);

    con.Open();
    int result = cmd.ExecuteNonQuery();
    if (result > 0)
    {
        // SUCCESS!
        con.Close();
        return true;
    }
    else
    {
        //failure
        con.Close();
        return false;
    }

}

要检索图像:

private Bitmap retrieveBitmap()
    {
        Image image1 = null
        if (dt1.Rows.Count > 0)
        {
            byte[] imageData1 = null;
            if (dt1[0].Count > 0)
            {
                if (!Information.IsDBNull(dt1.CopyToDataTable()[0].Item("File2")))
                {
                    imageData1 = (byte[])dt1.CopyToDataTable()[0].Item("File2");
                }
            }
            if ((imageData1 != null))
            {
                if (isValidImage(imageData1))
                {
                    using (MemoryStream ms = new MemoryStream(imageData1, 0, imageData1.Length))
                    {
                        ms.Write(imageData1, 0, imageData1.Length);
                        image1 = Image.FromStream(ms, true);
                    }
                    return image1;
                }
                else
                {
                    // "Invalid image on server";
                    return null;
                }
            }
        }
    }

我的代码可能需要进行小的格式更改,请编辑任何具有无效语法的内容(我的 C# 有点生疏,并且我的代码是通过转换器运行的)。

I just recently had to do the exact same thing in VB.NET. Here is my code, run through Telerik's Code Converter. It was quite tricky to get working, and is still honestly a pain.

To upload an image:

private bool uploadImage(ref Bitmap p)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = Configuration.ConfigurationManager.ConnectionStrings("ConnStringHere").ConnectionString;
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "INSERT INTO Table_Name (File2) VALUES (@File2)"; //I named the column File2 simply because "File" seemed to be a keyword in SQLServer
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;

    SqlParameter File1 = new SqlParameter("@File2", SqlDbType.Image);
    MemoryStream ms = new MemoryStream();

    using (Bitmap tempImage = new Bitmap(p))
    {
        tempImage.Save(ms, p.RawFormat);
    }

    byte[] data = ms.GetBuffer();
    if (!isValidImage(data)) //optional, will include code if requested.
    {
        return false;
    }
    File1.Value = data;
    cmd.Parameters.Add(File1);

    con.Open();
    int result = cmd.ExecuteNonQuery();
    if (result > 0)
    {
        // SUCCESS!
        con.Close();
        return true;
    }
    else
    {
        //failure
        con.Close();
        return false;
    }

}

To retrieve an image:

private Bitmap retrieveBitmap()
    {
        Image image1 = null
        if (dt1.Rows.Count > 0)
        {
            byte[] imageData1 = null;
            if (dt1[0].Count > 0)
            {
                if (!Information.IsDBNull(dt1.CopyToDataTable()[0].Item("File2")))
                {
                    imageData1 = (byte[])dt1.CopyToDataTable()[0].Item("File2");
                }
            }
            if ((imageData1 != null))
            {
                if (isValidImage(imageData1))
                {
                    using (MemoryStream ms = new MemoryStream(imageData1, 0, imageData1.Length))
                    {
                        ms.Write(imageData1, 0, imageData1.Length);
                        image1 = Image.FromStream(ms, true);
                    }
                    return image1;
                }
                else
                {
                    // "Invalid image on server";
                    return null;
                }
            }
        }
    }

My code may need small formatting changes, please edit whatever has invalid syntax (my C# is a little rusty, and my code was run through a converter).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文