从MySQL数据库获取图像 - C#

时间:2012-04-13 16:40:18

标签: c# mysql database

我必须在MySQL数据库中存储和恢复图像。为此,我使用了本页面上的说明:MySQL Forum,我可以通过以下代码成功存储Image:

SaveIamge:

    void SaveImage()
    {
        MemoryStream ms = new MemoryStream();
        pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        cmd = new MySqlCommand("INSERT INTO " + tableName + " ( Product, Manufacturer, Description, Price, Image) Values ('New_Product', 'New_Manufacturer', 'New_Description', '0', @Image)", conn);
        cmd.Parameters.Add(new MySqlParameter("@Image", Convert.ToBase64String(ms.ToArray())));
        cmd.ExecuteNonQuery();
    }

但是我无法从数据库中获取图像:我正在使用以下代码,请检查这里有什么问题:

GetThumbnail:

     void GetThumbnail()
     {
        string TN = tableNames[comboBox1.SelectedIndex];
        cmd = new MySqlCommand("SELECT Image FROM " + tableName + " WHERE Product = " + ProductTitle(), conn);
        object imgObj = cmd.ExecuteScalar();
        byte[] b = Convert.FromBase64String(Convert.ToString(imgObj));
        MemoryStream ms = new MemoryStream(b);
        pictureBox2.Image = Image.FromStream(ms);
    }

1 个答案:

答案 0 :(得分:5)

如何将图像存储到二进制字段中?它比Base64编码更有意义:

void SaveImage(byte[] image)
{
    using (var conn = new MySqlConnection(ConnectionString))
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "INSERT INTO pictures (Product, Manufacturer, Description, Price, Image) VALUES ('New_Product', 'New_Manufacturer', 'New_Description', '0', ?Image)";
        cmd.Parameters.Add("?Image", image);
        cmd.ExecuteNonQuery();    
    }
}

byte[] GetImage(string product)
{
    using (var conn = new MySqlConnection(ConnectionString))
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "SELECT Image FROM pictures WHERE Product = ?product";
        cmd.Parameters.Add("?product", product);
        using (var reader = cmd.ExecuteReader())
        {
            if (!reader.Read())
            {
                return null;
            }

            const int CHUNK_SIZE = 2 * 1024;
            byte[] buffer = new byte[CHUNK_SIZE];
            long bytesRead;
            long fieldOffset = 0;
            using (var stream = new MemoryStream())
            {
                while ((bytesRead = reader.GetBytes(reader.GetOrdinal("Image"), fieldOffset, buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, (int)bytesRead);
                    fieldOffset += bytesRead;
                }
                return stream.ToArray();
            }
        }
    }
}

然后:

using (var ms = new MemoryStream())
{
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    SaveImage(ms.ToArray());
}

当你想要检索时:

byte[] image = GetImage("New_Product");
MemoryStream stream = new MemoryStream(image);
pictureBox2.Image = Image.FromStream(ms);