简体   繁体   English

C#:图像调整大小并同时裁剪

[英]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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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