1

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

保存图片:

    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();
    }

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

获取缩略图:

     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);
    }
4

1 回答 1

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);
于 2012-04-13T16:57:35.953 回答