2008-12-03 34 views

回答

6

我发现这一点:http://channel9.msdn.com/forums/TechOff/108813-Bitmap-to-byte-array/

说,你可以使用一个MemoryStream和.Save方法它会是这样的:

System.Drawing.Bitmap bmp = GetTheBitmap(); 
System.IO.MemoryStream stream = new System.IO.MemoryStream(); 
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); 
stream.Position = 0; 
byte[] data = new byte[stream.Length]; 
stream.Read(data, 0, stream.Length); 
4

上Bitmap类使用LockBits成员获得的BitmapData,然后使用Scan0和Marshal.ReadByte来读取字节。下面是小例子(它是不是正确的亮度调整,虽然):

public static void AdjustBrightness(Bitmap image, int brightness) 
    { 
     int offset = 0; 
     brightness = (brightness * 255)/100; 
     // GDI+ still lies to us - the return format is BGR, NOT RGB. 
     BitmapData bmData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); 

     int stride = bmData.Stride; 
     IntPtr Scan0 = bmData.Scan0; 

     int nVal = 0; 
     int nOffset = stride - image.Width * 3; 
     int nWidth = image.Width * 3; 

     for (int y = 0; y < image.Height; ++y) 
     { 
      for (int x = 0; x < nWidth; ++x) 
      { 
       nVal = Marshal.ReadByte(Scan0, offset) + brightness; 

       if (nVal < 0) 
        nVal = 0; 
       if (nVal > 255) 
        nVal = 255; 

       Marshal.WriteByte(Scan0, offset, (byte)nVal); 
       ++offset; 
      } 
      offset += nOffset; 
     } 
     image.UnlockBits(bmData); 
    } 
4

如果您需要访问的像素信息,超慢,但超简单的方法是在调用与getPixel和SetPixel方法你的Bitmap对象。

超快而且不那么困难的方法是调用Bitmap的LockBits方法,并使用它返回的BitmapData对象直接读写Bitmap的字节数据。你可以做的Marshal类后者部分在伊利亚的例子,也可以跳过元帅开销是这样的:

BitmapData data; 
    int x = 0; //or whatever 
    int y = 0; 
    unsafe 
    { 
     byte* row = (byte*)data.Scan0 + (y * data.Stride); 
     int columnOffset = x * 4; 
     byte B = row[columnOffset]; 
     byte G = row[columnOffset + 1]; 
     byte R = row[columnOffset + 2]; 
     byte A = row[columnOffset + 3]; 
    } 
0

另一种解决方案是使用LockBits和Marshal.Copy你的位图转换成一个数组。我需要这种解决方案,因为我有两张只在颜色深度上有差异的图像,其他提供的解决方案处理得不好(或太慢)。

using (Bitmap bmp = new Bitmap(fname)) { 
    // Convert image to int32 array with each int being one pixel 
    int cnt = bmp.Width * bmp.Height * 4/4; 
    BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), 
          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); 
    Int32[] rgbValues = new Int32[cnt]; 

    // Copy the RGB values into the array. 
    System.Runtime.InteropServices.Marshal.Copy(bmData.Scan0, rgbValues, 0, cnt); 
    bmp.UnlockBits(bmData); 
    for (int i = 0; i < cnt; ++i) { 
     if (rgbValues[i] == 0xFFFF0000) 
      Console.WriteLine ("Red byte"); 
    } 
} 
相关问题