Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Bild aus MySQL-Datenbank abrufen – C#

Wie wäre es mit dem Speichern des Bildes in einem binären Feld? Es wäre sinnvoller als Base64-Codierung:

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

und dann:

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

und wann Sie abrufen möchten:

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