简体   繁体   中英

C#: Image resize and crop at the same time

I'm trying to write a very fast method for creating thumbnails. It will crop and resize an image at the same time. The result image will always be square-like. So having that in mind we can now look at my code :) It is working (as far as I can see):

    public static void CreateAndSaveThumbnail(string path, string output, int desiredSize)
    {
        using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path)))
        using (Bitmap src = new Bitmap(ms))
        {
            Rectangle crop = src.Width > src.Height ?
                new Rectangle((src.Width - src.Height) / 2, 0, src.Height, src.Height) :
                new Rectangle(0, 0, src.Width, src.Width);

            int size = Math.Min(desiredSize, crop.Width);

            using (Bitmap cropped = src.Clone(crop, src.PixelFormat))
            using (Bitmap resized = new Bitmap(size, size))
            using (Graphics g = Graphics.FromImage(resized))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(cropped, 0, 0, size, size);
                resized.Save(output, ImageFormat.Jpeg);
            }
        }
    }

So how the code above works? It crops the middle part for landscape images and top part for portrait images. So this is a standard behavior. Then it resizes the cropped image (it is already a square).

Is this code OK? Could it be faster? How? Any optimizations possible?

Your routine works great but for one slight problem, at least in my desired application. I wanted the routine to crop portrait bitmaps the same as you do for landscape bitmaps; by cropping off half of the excess from the top and half of excess from the bitmap. So I simply duplicated the landscape crop code to the portrait crop code and adjusted as necessary resulting in this:

Rectangle crop = src.Width > src.Height ?
new Rectangle((src.Width - src.Height) / 2, 0, src.Height, src.Height) :
new Rectangle(0, (src.Height - src.Width) / 2, src.Width, src.Width);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM