How to crop an image using C#?

后端 未结 14 848
忘掉有多难
忘掉有多难 2020-11-22 05:16

How can I write an application that will crop images in C#?

14条回答
  •  礼貌的吻别
    2020-11-22 05:53

    use bmp.SetResolution(image.HorizontalResolution, image .VerticalResolution);

    this may be necessary to do even if you implement best answer here especially if your image is real great and resolutions are not exactly 96.0

    My test example:

        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");
                }
            }
        }
    

提交回复
热议问题