2017-05-10 4 views
0

PixelFormat의 System.Drawing.Bitmap이 Format32bppRgb입니다. 이 이미지를 8 비트의 회색조 비트 맵으로 변환하고 싶습니다.32 비트 System.Drawing.Bitmap을 8bit로 변환

내가 지금 시도하고 8 비트로 변환이 방법을 사용하는 경우 : Bitmap 내가 끝낼 그러나

public static Bitmap ToGrayscale(Bitmap bmp) 
     { 
      int rgb; 
      System.Drawing.Color c; 

      for (int y = 0; y < bmp.Height; y++) 
       for (int x = 0; x < bmp.Width; x++) 
       { 
        c = bmp.GetPixel(x, y); 
        rgb = (int)((c.R + c.G + c.B)/3); 
        bmp.SetPixel(x, y, System.Drawing.Color.FromArgb(rgb, rgb, rgb)); 
       } 
      return bmp; 
     } 

여전히 Format32bppRgb의 PixelFormat 속성이있다. 이 정보는 BitmapInfoHeader에서 오는 것입니까? 이것을 수동으로 조작해야합니까? 입력 해 주셔서 감사합니다!

답변

1

Bitmap의 새 인스턴스를 만들고 반환해야합니다.

PixelFormat은 Bitmap 생성자에서 지정되며 변경할 수 없습니다.

편집 : this answer on MSDN에 따라 샘플 코드 :

public static Bitmap ToGrayscale(Bitmap bmp) { 
     var result = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format8bppIndexed); 

     BitmapData data = result.LockBits(new Rectangle(0, 0, result.Width, result.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); 

     // Copy the bytes from the image into a byte array 
     byte[] bytes = new byte[data.Height * data.Stride]; 
     Marshal.Copy(data.Scan0, bytes, 0, bytes.Length); 

     for (int y = 0; y < bmp.Height; y++) { 
      for (int x = 0; x < bmp.Width; x++) { 
       var c = bmp.GetPixel(x, y); 
       var rgb = (byte)((c.R + c.G + c.B)/3); 

       bytes[x * data.Stride + y] = rgb; 
      } 
     } 

     // Copy the bytes from the byte array into the image 
     Marshal.Copy(bytes, 0, data.Scan0, bytes.Length); 

     result.UnlockBits(data); 

     return result; 
    } 
+0

감사합니다. PixelFormat'Format8bppIndexed'를 사용하여 새 비트 맵을 만드는 경우'SetPixel' 메서드를 사용하면 예외가 발생합니다 :'SetPixel은 인덱싱 된 픽셀 형식을 가진 이미지에는 지원되지 않습니다 .' – tzippy

+0

@tzippy 편집시 샘플 코드 살펴보기 섹션 – TcKs

관련 문제