2017-04-16 43 views
0

下圖顯示了轉換大小爲1x2的24位彩色圖像時發生的情況。無論顏色深度如何,圖像都佔用相同的字節數

enter image description here

下圖顯示了轉換大小爲1x2的32位彩色圖像時發生的情況。

enter image description here

我想,24位圖像將佔據6個字節。但是,兩者都佔用8個字節。

因此,我的C#代碼失敗。因爲它假定像素需要(ColorDepth/8)*Width*Height字節數。

public static int[,] ToInteger(Bitmap bitmap) 
    { 
     BitmapLocker locker = new BitmapLocker(bitmap); 

     locker.Lock(); 

     byte[] data = locker.ImageData; 
     int Width = locker.Width; 
     int Height = locker.Height; 
     int noOfBytesPerPixel = locker.BytesPerPixel; 
     int[,] integerImage = new int[Width, Height]; 
     int byteCounter = 0; 

     for (int i = 0; i < Width; i++) 
     { 
      for (int j = 0; j < Height; j++) 
      { 
       int integer = BitConverter.ToInt32(data, byteCounter); 

       integerImage[i, j] = integer; 

       byteCounter += noOfBytesPerPixel; 
      } 
     } 

     locker.Unlock(); 

     return integerImage; 
    } 

那麼,究竟發生了什麼呢?

+0

也許它的內存對齊方式:https://en.wikipedia.org/wiki/Data_structure_alignment –

+1

看看[步幅](http://stackoverflow.com/questions/24595836/size-of-bitmap-byte-differs-從BMP-MemoryStream的尺寸/ 24595963#24595963)! – TaW

回答

1

爲什麼圖像佔用相同的字節數?

我們不能肯定地告訴你既然沒有顯示你如何取得他們(也許他們得到的默認設置,以最快的速度處理,像WriteableBitmapEx例如晉升爲32bpp的?)

適當公式來計算每個像素的字節數:

bytesPerPixel =(bitsPerPixel + 7)/ 8

這裏是一個將轉換無論是從8到32 BPP到int一個例子:

private static void DoWork(Bitmap bitmap) 
{ 
    var width = bitmap.Width; 
    var height = bitmap.Height; 
    var rectangle = new Rectangle(0, 0, width, height); 
    var data = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, bitmap.PixelFormat); 

    var bitsPerPixel = GetBitsPerPixel(bitmap.PixelFormat); 
    var bytesPerPixel = (bitsPerPixel + 7)/8; 
    var stride = data.Stride; 
    var length = stride * data.Height; 
    var pixels = new byte[length]; 
    Marshal.Copy(data.Scan0, pixels, 0, length); 

    for (var y = 0; y < height; y++) 
    for (var x = 0; x < width; x++) 
    { 
     var offset = y * stride + x * bytesPerPixel; 
     var value = 0; 
     for (var i = 0; i < bytesPerPixel; i++) 
      value |= pixels[offset + i] << i; 
    } 
    bitmap.UnlockBits(data); 
} 

private static int GetBitsPerPixel(PixelFormat format) 
{ 
    switch (format) 
    { 
     case PixelFormat.Format8bppIndexed: 
      return 1; 
     case PixelFormat.Format16bppRgb555: 
      return 2; 
     case PixelFormat.Format24bppRgb: 
      return 24; 
     case PixelFormat.Format32bppRgb: 
      return 32; 
     default: // TODO 
      throw new NotSupportedException(); 
    } 
} 

(不知道是否有用,雖然)

注:我「仿真」是什麼是必要的,因爲我沒有像你那樣使用BitmapLocker班。

+0

單色和4位圖像怎麼樣? – anonymous

+0

你能更精確嗎? – Aybe

+0

此源代碼無法處理1位單色圖像和4位/ 16色圖像。 – anonymous