简体   繁体   中英

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM