2011-12-08 5 views
2

이 함수로 비트 맵을 자르기를 원하지만 비트 맵이 자르기 영역보다 작을 수 있으므로이 경우 비트 맵을 더 크게 만들려고합니다.비트 맵 자르기 및 필요한 경우 크기 확장

예를 들어 비트 맵이 200x250이고 250x250의 CropBitmap 메서드를 사용하면 메모리 부족 오류가 발생합니다. 누락 된 왼쪽 50 픽셀이 흰색으로 채워지는 250x250의 비트 맵을 반환해야합니다.

어떻게하면됩니까?

public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight) 
{ 
    var rect = new Rectangle(cropX, cropY, cropWidth, cropHeight); 

    if(bitmap.Width < cropWidth || bitmap.Height < cropHeight) 
    { 
     // what now? 
    } 

    return bitmap.Clone(rect, bitmap.PixelFormat); 
} 
+0

이렇게하면 크기를 조정할 때 도움이됩니다. http://snippets.dzone.com/posts/show/4336 – ThePower

답변

3

적절한 크기의 새 비트 맵을 만듭니다. 그런 다음 System.Drawing.Graphics을 가져 와서 흰색 영역을 만들고 소스 이미지를 삽입하십시오. 이런 식으로 뭔가 :

if (bitmap.Width < cropWidth && bitmap.Height < cropHeight) 
    { 
     Bitmap newImage = new Bitmap(cropWidth, cropHeight, bitmap.PixelFormat); 
     using (Graphics g = Graphics.FromImage(newImage)) 
     { 
      // fill target image with white color 
      g.FillRectangle(Brushes.White, 0, 0, cropWidth, cropHeight); 

      // place source image inside the target image 
      var dstX = cropWidth - bitmap.Width; 
      var dstY = cropHeight - bitmap.Height; 
      g.DrawImage(bitmap, dstX, dstY); 
     } 
     return newImage; 
    } 

참고, 내가 &&와 외부 if 표현에 ||를 대체있다. ||과 작동하게하려면 소스 영역을 계산하고 사용해야합니다. another overload of Graphics.DrawImage

+0

'dstX = cropWidth - bitmap.Width'를'dstX = bitmap.Width - cropWidth'로 설정했으나 효과가있었습니다 - 고마워요! (그리고 dstY와 동일) – Marc