2016-08-04 3 views
-1
public static bool IsGrayscale(Bitmap bitmap) 
    { 
     return bitmap.PixelFormat == PixelFormat.Format8bppIndexed ? true : false; 
    } 

.비트 맵에서 정수 루틴 생성 예외

public static int[,] ToInteger(Bitmap image) 
    { 
     if (Grayscale.IsGrayscale(image)) 
     { 
      Bitmap bitmap = (Bitmap)image.Clone(); 

      int[,] array2d = new int[bitmap.Width, bitmap.Height]; 

      BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), 
                ImageLockMode.ReadWrite, 
                PixelFormat.Format8bppIndexed); 
      int bytesPerPixel = sizeof(byte); 

      unsafe 
      { 
       byte* address = (byte*)bitmapData.Scan0; 

       int paddingOffset = bitmapData.Stride - (bitmap.Width * bytesPerPixel); 

       for (int i = 0; i < bitmap.Width; i++) 
       { 
        for (int j = 0; j < bitmap.Height; j++) 
        { 
         int iii = 0; 

         //If there are more than 1 channels... 
         //(Would actually never occur) 
         if (bytesPerPixel >= sizeof(int)) 
         { 
          byte[] temp = new byte[bytesPerPixel]; 

          //Handling the channels. 
          //PixelFormat.Format8bppIndexed == 1 channel == 1 bytesPerPixel == byte 
          //PixelFormat.Format32bpp  == 4 channel == 4 bytesPerPixel == int 
          for (int k = 0; k < bytesPerPixel; k++) 
          { 
           temp[k] = address[k]; 
          } 

          iii = BitConverter.ToInt32(temp, 0); 
         } 
         else//If there is only one channel: 
         { 
          iii = (int)(*address); 
         } 

         array2d[i, j] = iii; 

         address += bytesPerPixel; 
        } 

        address += paddingOffset; 
       } 
      } 

      bitmap.UnlockBits(bitmapData); 

      return array2d; 
     } 
     else 
     { 
      throw new Exception("Not a grayscale"); 
     } 
    } 

다음 행의 예외 :

iii = (int)(*address); 

'System.AccessViolationException' 유형의 처리되지 않은 예외가 고속 푸리에 Transform.exe

부가 정보 발생하려고 보호 된 메모리를 읽거나 씁니다. 이것은 종종 다른 메모리가 손상되었음을 나타냅니다.

enter image description here

그 예외의 원인은 무엇인가?

어떻게 해결할 수 있습니까?

.

.

P. 나는 다음 PNG 이미지를 사용하고 있습니다 : 당신은 당신의 루프에서 bitmap.Height에 대한 bitmap.Width을 착각

enter image description here

+0

포인터를 직접 사용하려면 코드 섹션을 안전하지 않은 것으로 선언해야합니다. – Kevin

+0

@ 케빈, 나는 이미 그것을 안전하지 않다고 선언했다. 그렇지 않으면 실행되어서는 안됩니다. – anonymous

+0

예제 사진을 게시 할 수 있습니까? 나에게 코드가 잘 작동하기 때문에 – technikfischer

답변

2

. 스트라이드는 전체 너비와 이미지의 오프셋을 나타내므로 바깥 쪽 루프의 높이와 안쪽 루프의 너비를 반복해야합니다. 그런 다음 통과 된 각 줄 대신 줄 단위로 padding을 추가 할 수 있습니다. 따라서

for (int i = 0; i < bitmap.Height; i++) 
{ 
    for (int j = 0; j < bitmap.Width; j++) 
    { 

이 작동 중입니다. 또한 색인이 이제 이미지의 다른 차원에 속하기 때문에 array2d[i, j] = iii에서 array2d[j, i] = iii으로 배열 액세스를 교환해야합니다.

+0

으로 표시해주세요. 또한 일반적으로 x 및 y를 반복 할 때 ... 루프 변수 'x' 및'y'_를 호출합니다. . 코드를 훨씬 더 간단하게 만듭니다. – Nyerguds

관련 문제