1

画像処理用の LockBitmap クラスを学習しようとしていますが、以下に投稿されたこのコードに出くわしました。基本的に、xy 座標の色を返します。

もちろん、この方法はsource.LockBits()and Marshal.Copy()/を実行した後にのみ機能しunsafe contextます。

public Color GetPixel(int x, int y, Bitmap source)
{
    int Depth = System.Drawing.Bitmap.GetPixelFormatSize(source.PixelFormat);
    int Width = source.Width;
    int Height = source.Height;
    Color clr = Color.Empty;

    // Get color components count
    int cCount = Depth / 8;
    int PixelCounts = Width * Height;
    byte[] Pixels = new byte[cCount * PixelCounts];

    // Get start index of the specified pixel
    int i = ((y * Width) + x) * cCount;

    byte b = Pixels[i];
    byte g = Pixels[i + 1];
    byte r = Pixels[i + 2];
    byte a = Pixels[i + 3]; // a
    clr = Color.FromArgb(a, r, g, b);

    return clr;
}
  1. は何ですかcCount、なぜいつもDepth / 8ですか?
  2. int i = ((y * Width) + x) * cCount、これは (x,y) 座標から に変換する固定式Pixels[i]ですか? なんで?
4

2 に答える 2

0
  1. いつもではありませんので、こちらをご覧ください。これはあなたの実装よりも優れているかもしれません。

    色情報には 8 (または 16 など) バイトが必要なため、8、16、24、32 などになります。

投稿されたソースのコード例:

 // Get start index of the specified pixel
        int i = ((y * Width) + x) * cCount;

        if (i > Pixels.Length - cCount)
            throw new IndexOutOfRangeException();

        if (Depth == 32) // For 32 bpp get Red, Green, Blue and Alpha
        {
            byte b = Pixels[i];
            byte g = Pixels[i + 1];
            byte r = Pixels[i + 2];
            byte a = Pixels[i + 3]; // a
            clr = Color.FromArgb(a, r, g, b);
        }
        if (Depth == 24) // For 24 bpp get Red, Green and Blue
        {
            byte b = Pixels[i];
            byte g = Pixels[i + 1];
            byte r = Pixels[i + 2];
            clr = Color.FromArgb(r, g, b);
        }
        if (Depth == 8)
        // For 8 bpp get color value (Red, Green and Blue values are the same)
        {
            byte c = Pixels[i];
            clr = Color.FromArgb(c, c, c);
  1. ビットマップは配列としてメモリに格納されるためです。

    (y * 幅) は寸法、+ x) は寸法のピクセル、* cCount はピクセルあたりのステップです。(すべてのピクセルには、メモリ内の cCount バイトが必要です。)

すべてのピクセルを一列に並べると考えてください。左下から始まり、左上に移動し、2 行目左下から 2 行目上下部に移動し、右上に到達するまで続きます。

于 2016-03-22T09:25:29.683 に答える