2017-12-21 1 views
0

바이트 배열에서 비트 맵을 만들려면 this answer과 같은 메서드를 사용하고 있습니다.C#의 RGB 배열에서 비트 맵 만들기, 결과 이미지의 차이가 있습니까?

int width = 20; 
int height = 30; 
int bytesPerPixel = 3; 
int bytesPerRow = width * bytesPerPixel; 
int totalLength = bytesPerRow * height;    
byte[] managedArray = new byte[totalLength]; 

// fill background with white 
for (int i = 0; i < totalLength; i++) 
    managedArray[i] = 255; 

// draw on each row 
for (int i = 0; i < height; i++) 
{ 
    // first pixel is green 
    managedArray[0 + i * bytesPerRow] = 0; 
    managedArray[1 + i * bytesPerRow] = 255; 
    managedArray[2 + i * bytesPerRow] = 0; 
    // last pixel is red 
    managedArray[bytesPerRow - 3 + i * bytesPerRow] = 0; 
    managedArray[bytesPerRow - 2 + i * bytesPerRow] = 0; 
    managedArray[bytesPerRow - 1 + i * bytesPerRow] = 255; 
} 
MySaveBMP(managedArray, width, height); 

얻어진 20x30의 BMP 이미지는 다음과 같다 :

private static void MySaveBMP(byte[] buffer, int width, int height) 
{ 
    Bitmap b = new Bitmap(width, height, PixelFormat.Format24bppRgb); 
    Rectangle BoundsRect = new Rectangle(0, 0, width, height); 
    BitmapData bmpData = b.LockBits(BoundsRect, 
            ImageLockMode.WriteOnly, 
            b.PixelFormat); 
    IntPtr ptr = bmpData.Scan0; 

    // fill in rgbValues 
    Marshal.Copy(buffer, 0, ptr, buffer.Length); 
    b.UnlockBits(bmpData); 
    b.Save(@"D:\myPic.bmp", ImageFormat.Bmp);   
} 

와 나는 같이 일부 값을 작성 바이트 배열을 생성하지만

20x30 bmp image

, 만약 I 이미지 높이를 변경하면 (예 : 21) 결과 이미지가 손상된 것처럼 보입니다.

21x30 bmp image

비트 맵 이미지를 만드는 동안 내가 잘못 뭐하는 거지 : 그것은 조금 왼쪽으로 이동처럼 각 행이 보인다?

+1

MySaveBMP를 호출하는 코드는 어디에 있습니까? 또한 +와 - 사이의 작업 순서를 명확히하기 위해 "마지막 픽셀은 빨간색"아래에 괄호를 추가합니다. 그것이 당신의 문제라고 생각하지 마십시오. 그러나 – zzxyz

답변

1

답변을 찾은 것 같습니다. 속성을 알지 못했기 때문에 .

private static void MySaveBMP(byte[] buffer, int width, int height) 
    { 
     Bitmap b = new Bitmap(width, height, PixelFormat.Format24bppRgb); 

     Rectangle BoundsRect = new Rectangle(0, 0, width, height); 
     BitmapData bmpData = b.LockBits(BoundsRect, 
             ImageLockMode.WriteOnly, 
             b.PixelFormat); 

     IntPtr ptr = bmpData.Scan0; 

     // add back dummy bytes between lines, make each line be a multiple of 4 bytes 
     int skipByte = bmpData.Stride - width*3; 
     byte[] newBuff = new byte[buffer.Length + skipByte*height]; 
     for (int j = 0; j < height; j++) 
     { 
      Buffer.BlockCopy(buffer, j * width * 3, newBuff, j * (width * 3 + skipByte), width * 3); 
     } 

     // fill in rgbValues 
     Marshal.Copy(newBuff, 0, ptr, newBuff.Length); 
     b.UnlockBits(bmpData); 
     b.Save(@"D:\myPic.bmp", ImageFormat.Bmp);   
    } 

또 다른 해결책은 내가 그래서 내가 귀찮게 할 필요가 없습니다 PixelFormatFormat32bppPArgb로 변경 4. bytesPerPixel을 변경한다는 것입니다 : 누군가가 here.

기능 저장 수정 여기 내 답이있다 4 바이트 스캔 라인 형식

+0

예, 'Stride'는 알아 내기가 정말 기이합니다. 기본적으로 4 바이트로 정렬됩니다. 그것은 결코 _count_, 그리고 항상 그냥 bitmapdata 개체에서 보폭을 요청하십시오. 색인화 된 이미지로 작업했으며 4 비트 및 1 비트 이미지에서는 규칙을 따르지 않습니다. – Nyerguds

관련 문제