Mohamed Kamal
Mohamed Kamal

Reputation: 1627

The output image after cropping is larger than the original size

When I crop an Image using Bitmap.Clone() it creates output larger than the original image Size
The Original size is : 5 M
and the Output Cropped image is : 28 M

How can I make cropping without losing quality and with no large size? My code is :

private static Image cropImage(Image img, Rectangle cropArea)
{
  var bmpImage = new Bitmap(img);
  Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
  img.Dispose();
  bmpCrop.Save(@"D:\Work\CropImage\CropImage\crop.jpg",bmpImage.RawFormat );
  return (Image)(bmpCrop);
}

 static void Main(string[] args)
        {
            string sourceimg = @"D:\Work\Crop Image\CropImage\4032x5808.jpg";
            Image imageoriginal = Image.FromFile(sourceimg);
            int HorX,HorY,VerX,VerY;
            Console.WriteLine("Enter X 1 Cor. ");
            HorX=int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Y 1 Cor. ");
            HorY=int.Parse(Console.ReadLine());
            Console.WriteLine("Enter X 2 Cor. ");
            VerX=int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Y 1 Cor. ");
            VerY= int.Parse(Console.ReadLine());
            Rectangle rect = new Rectangle(HorX,HorY,VerX,VerY);
            cropImage(imageoriginal, rect);
        }

Upvotes: 0

Views: 1435

Answers (2)

Nogard
Nogard

Reputation: 1789

Usually you don't need to worry about reducing quality when cropping as you simply save part of the original image with 1:1 ratio.

Your sample works fine - problem must be in Rectangle input part. As your variable names are confusing I would like to recommend reading about it at MSDN.

To be sure, just initialize your rectangle (assume that your image is greater than 1000x900 ) with new Rectangle(200,100,800,800); This will crop region starting from 200th pixel from the left and 100th pixel from the top with width and height equal to 800 pixels.

Final quality will remain the same and image size will be smaller.

Upvotes: 0

Ross Dargan
Ross Dargan

Reputation: 6021

You are saving the image as a bitmap, not a jpg, or png which is probably your input format. Change the format type and you will see the file size plummet!

This code sample should help you set the quality:-

var qualityEncoder = Encoder.Quality;
var quality = (long)<desired quality>;
var ratio = new EncoderParameter(qualityEncoder, quality );
var codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg">;
bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG

Upvotes: 6

Related Questions