SWDeveloper
SWDeveloper

Reputation: 339

Convert bitmap to png image and save in database

I have a bitmap image. I want to compress it into a png image so that it will consume less memory while saving it in database.

During my research, I get lot of options to save it as a file in hard disk. I want to return the png image from a method.

Upvotes: 0

Views: 1938

Answers (1)

Margus
Margus

Reputation: 20048

To get png byte array from png source

public byte[] GetPng(string filename)
{
    using (var bitmap = new Bitmap(filename))
    using (var stream = new MemoryStream())
    {
        bitmap.Save(stream, ImageFormat.Png);
        return stream.ToArray();
    }
}

With Dapper ORM

var sql = "INSERT INTO [dbo].[Images]([FullName], [Data]) VALUES (@FullName, @Data)";
var result = db.Execute(sql, new
{
    FullName = filename,
    Data = GetPng(filename)
});

Upvotes: 1

Related Questions