Home > Database > Mysql Tutorial > PictureBox中的Image对象转存到数据库

PictureBox中的Image对象转存到数据库

WBOY
Release: 2016-06-07 15:48:03
Original
1263 people have browsed it

这个是在百度知道上回答问题时看到的,一时没有做出来,看了一些资料才弄清楚的。 主要有两个点: 1.对流的操作不熟悉,不知道图片Image对象是可以”保存“到MemoryStream中的; image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg); 2.二进制数

这个是在百度知道上回答问题时看到的,一时没有做出来,看了一些资料才弄清楚的。

主要有两个点:

1.对流的操作不熟悉,不知道图片Image对象是可以”保存“到MemoryStream中的;

image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
Copy after login

2.二进制数据插入到数据库的操作不清楚。

SqlParameter param = new SqlParameter("ImgData", SqlDbType.VarBinary, imageBytes.Length);
param.Value = imageBytes;
cmd.Parameters.Add(param);
Copy after login

下面贴上代码

private void button1_Click(object sender, EventArgs e)
        {
            byte[] imageBytes = GetImageBytes(pictureBox1.Image);

            string connStr = "SQL Server连接字符串";

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "Insert Into T_Img Values (@ImgData) ";
                using (SqlCommand cmd = new SqlCommand(sql))
                {
                    SqlParameter param = new SqlParameter("ImgData", SqlDbType.VarBinary, imageBytes.Length);
                    param.Value = imageBytes;
                    cmd.Parameters.Add(param);

                    cmd.Connection = conn;
                    conn.Open();
                    int i = cmd.ExecuteNonQuery();
                    MessageBox.Show(i.ToString());
                }
            }
        }
        private byte[] GetImageBytes(Image image)
        {
            MemoryStream mstream = new MemoryStream();
            image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] byteData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byteData, 0, byteData.Length);
            mstream.Close();
            return byteData;
        }
Copy after login

                   

                                              PictureBox中的Image对象转存到数据库

上传了源代码:http://download.csdn.net/detail/frombegintoend/4403728

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template