[转载]Converting a bitmap to a byte array

本文介绍两种将位图(Bitmap)转换为字节数组(byte[])的方法:一种是通过锁定位图并直接复制内存的方式实现;另一种是利用MemoryStream进行位图的保存与读取。此外还提供了从字节数组还原位图的方法。

出自 OceanChip http://www.cnblogs.com/Oceanchip/archive/2006/12/06/583758.html

 

方法一:

ContractedBlock.gif ExpandedBlockStart.gif Code
// import this 
// using System.Runtime.InteropServices;
private unsafe byte[] BmpToBytes_Unsafe (Bitmap bmp)
{
    BitmapData bData 
= bmp.LockBits(new Rectangle (new Point(), bmp.Size),
        ImageLockMode.ReadOnly, 
        PixelFormat.Format24bppRgb);
    
// number of bytes in the bitmap
    int byteCount = bData.Stride * bmp.Height;
    
byte[] bmpBytes = new byte[byteCount];

    
// Copy the locked bytes from memory
    Marshal.Copy (bData.Scan0, bmpBytes, 0, byteCount);

    
// don't forget to unlock the bitmap!!
    bmp.UnlockBits (bData);

    
return bmpBytes;
}

 

in most cases this works fine, because your bitmap doesn't have an alpha channel. But if it does, and you want to preserve it, then use Format32bppArgb in the fist line when locking the bitmap.
I wish I could think of a way of doing this without locking the bitmap (ie, you could use GCHandle.Alloc() and then call Marshal.Copy() using the created handle, but the problem is I wouldnt know the size of the bitmap without locking it's bits and the Marshal.Copy() function needs to know the size).

 

ContractedBlock.gif ExpandedBlockStart.gif Code
private unsafe Bitmap BytesToBmp (byte[] bmpBytes, Size imageSize)
{
    Bitmap bmp 
= new Bitmap (imageSize.Width, imageSize.Height);

    BitmapData bData  
= bmp.LockBits (new Rectangle (new Point(), bmp.Size),
        ImageLockMode.WriteOnly,
        PixelFormat.Format24bppRgb);

    
// Copy the bytes to the bitmap object
    Marshal.Copy (bmpBytes, 0, bData.Scan0, bmpBytes.Length);
    bmp.UnlockBits(bData);
    
return bmp;
}

 

方法二:

 

ContractedBlock.gif ExpandedBlockStart.gif Code
// Bitmap bytes have to be created via a direct memory copy of the bitmap
private byte[] BmpToBytes_MemStream (Bitmap bmp)
{
    MemoryStream ms 
= new MemoryStream();
    
// Save to memory using the Jpeg format
    bmp.Save (ms, ImageFormat.Jpeg);
    
    
// read to end
    byte[] bmpBytes = ms.GetBuffer();
    bmp.Dispose();
    ms.Close();

    
return bmpBytes;
}


//Bitmap bytes have to be created using Image.Save()
private Image BytesToImg (byte[] bmpBytes)
{
    MemoryStream ms 
= new MemoryStream(bmpBytes);
    Image img 
= Image.FromStream(ms);
    
// Do NOT close the stream!
    
    
return img;
}

 

 

转载于:https://www.cnblogs.com/mishy/archive/2008/09/10/1288185.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值