BitmapExtensions Crop/SaveJpeg

Sep 14, 2011 at 8:53 PM

        public static Bitmap Crop(this Bitmap bitmap, Rectangle rectangle)
        {
            var clipRegion = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            clipRegion.Intersect(rectangle);

            return bitmap.Clone(clipRegion, bitmap.PixelFormat);
        }

        public static Bitmap Crop(this Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
        {
            return bitmap.Clone(new Rectangle(cropX, cropY, cropWidth, cropHeight), bitmap.PixelFormat);
        }


        public static void SaveJpeg(this Bitmap bmp, string filename, byte quality)
        {
            //ensure the quality is within the correct range
            if ((quality < 0) || (quality > 100))
                throw new ArgumentOutOfRangeException(
                    string.Format(
                        "Jpeg image quality must be between 0 and 100, with 100 being the highest quality.  A value of {0} was specified.",
                        quality));

            //create a collection of all parameters that we will pass to the encoder
            var encoderParameters = new EncoderParameters(1);

            //set the quality parameter for the codec
            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long) quality);

            //save the image using the codec and the parameters
            bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
        }

        internal static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            return ImageCodecInfo.GetImageDecoders().FirstOrDefault(codec => codec.FormatID == format.Guid);
        }