user1479013
user1479013

Reputation: 145

Convert Bitmap to byte

I'm using winform (C#). I have image as a bitmap and I want convert bitmap to byte to insert into Database. So, could you please tell me how to do?

Upvotes: 0

Views: 22472

Answers (3)

4b0
4b0

Reputation: 22323

You can use Bitmap.Save to save the contents of the bitmap to a stream. You can use this with a MemoryStream like this:

    MemoryStream memoryStream = new MemoryStream();
    Bitmap newBitmap = new Bitmap();
    newBitmap.Save(memoryStream, ImageFormat.Bmp);
    byte[] bitmapRecord = memoryStream.ToArray();

Upvotes: 1

Adil
Adil

Reputation: 148110

You can use ImageConverter get byte array form imaage

public static byte[] GetBytesOfImage(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

OR you can Use BitmapImage to do conversion.

Use these two methods to convert bitmap to byte array and byte array to bitmap.

public Byte[] BufferFromImage(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}
public BitmapImage ImageFromBuffer(Byte[] bytes)
{
    MemoryStream stream = new MemoryStream(bytes);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = stream;
    image.EndInit();
    return image;
}

Upvotes: 6

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32094

You can use the following code for this:

Bitmap myBitmap = ...;
var imageStream = new MemoryStream();
using (imageStream)
{
    // Save bitmap in some format.
    myBitmap.Save(imageStream, ImageFormat.Jpeg);
    imageStream.Position = 0;

    // Do something with the memory stream. For example:
    byte[] imageBytes = imageStream.ToArray();
    // Save bytes to the database.
}

As a side note, I do not know how large your images will be and what database you use, but storing large blobs in a database is usually not a good idea performance-wise. File system performance is a lot better for large blobs than database performance. SQL Server has direct support for transactionally storing blobs on the file system (and they suggest using it for files 1MB and larger).

I've seen serious read performance degradation in SQL Server Compact when storing files in the database. I don't know how other databases perform when storing large blobs.

Another possible solution is to store images on the file system and have pointers in your database to the files.

Upvotes: 1

Related Questions