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

 

方法一:

[] 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).

 

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

 

方法二:

 

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

 

 

相关文章: