[C#] C #을 사용하여 이미지를 자르는 방법?

C #에서 이미지를 자르는 응용 프로그램을 작성하려면 어떻게해야합니까?



답변

Graphics.DrawImage비트 맵에서 그래픽 객체에 자른 이미지를 그리는 데 사용할 수 있습니다 .

Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

using(Graphics g = Graphics.FromImage(target))
{
   g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height),
                    cropRect,
                    GraphicsUnit.Pixel);
}


답변

이 링크를 확인하십시오 : http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-izing

private static Image cropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
}


답변

허용 된 답변보다 간단합니다.

public static Bitmap cropAtRect(this Bitmap b, Rectangle r)
{
    using (Bitmap nb = new Bitmap(r.Width, r.Height))
    using (Graphics g = Graphics.FromImage(nb))
    {
        g.DrawImage(b, -r.X, -r.Y);
        return nb;
    }
}

그리고 그것은 “피할 아웃 메모리의 가장 간단한 대답은”예외 위험을.

그 참고 Bitmap하고 Graphics있습니다 IDisposable따라서 using조항.

편집 : 이것은 Bitmap.SavePaint.exe로 저장 한 PNG 또는 괜찮습니다. 그러나 Paint Shop Pro 6으로 저장 한 PNG에서는 실패 합니다 . 내용이 바뀌 었습니다 . 를 추가 GraphicsUnit.Pixel하면 다른 잘못된 결과가 나타납니다. 아마도 이러한 실패한 PNG에 결함이있을 수 있습니다.


답변

사용하다 bmp.SetResolution(image.HorizontalResolution, image .VerticalResolution);

특히 이미지가 실제로 훌륭하고 해상도가 정확히 96.0이 아닌 경우 여기에 최고의 답변을 구현 하더라도이 작업이 필요할 수 있습니다.

내 테스트 예 :

    static Bitmap LoadImage()
    {
        return (Bitmap)Bitmap.FromFile( @"e:\Tests\d_bigImage.bmp" ); // here is large image 9222x9222 pixels and 95.96 dpi resolutions
    }

    static void TestBigImagePartDrawing()
    {
        using( var absentRectangleImage = LoadImage() )
        {
            using( var currentTile = new Bitmap( 256, 256 ) )
            {
                currentTile.SetResolution(absentRectangleImage.HorizontalResolution, absentRectangleImage.VerticalResolution);

                using( var currentTileGraphics = Graphics.FromImage( currentTile ) )
                {
                    currentTileGraphics.Clear( Color.Black );
                    var absentRectangleArea = new Rectangle( 3, 8963, 256, 256 );
                    currentTileGraphics.DrawImage( absentRectangleImage, 0, 0, absentRectangleArea, GraphicsUnit.Pixel );
                }

                currentTile.Save(@"e:\Tests\Tile.bmp");
            }
        }
    }


답변

아주 쉽습니다 :

  • Bitmap자른 크기 로 새 객체를 만듭니다 .
  • 새 비트 맵에 대한 객체 Graphics.FromImage를 만드는 데 사용 합니다 Graphics.
  • DrawImage방법을 사용하면 음의 X 및 Y 좌표로 비트 맵에 이미지를 그릴 수 있습니다.

답변

다음은 이미지 자르기에 대한 간단한 예입니다.

public Image Crop(string img, int width, int height, int x, int y)
{
    try
    {
        Image image = Image.FromFile(img);
        Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
        bmp.SetResolution(80, 60);

        Graphics gfx = Graphics.FromImage(bmp);
        gfx.SmoothingMode = SmoothingMode.AntiAlias;
        gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
        gfx.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
        // Dispose to free up resources
        image.Dispose();
        bmp.Dispose();
        gfx.Dispose();

        return bmp;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return null;
    }
}


답변

AForge.NET을 사용하는 경우 :

using(var croppedBitmap = new Crop(new Rectangle(10, 10, 10, 10)).Apply(bitmap))
{
    // ...
}