繁体   English   中英

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

[英]C#: Image resize and crop at the same time

我正在尝试编写一种非常快速的方法来创建缩略图。 它将同时裁剪和调整图像大小。 结果图像将始终为方形。 所以考虑到这一点,我们现在可以查看我的代码:)它正在工作(据我所知):

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

那么上面的代码如何工作? 它用于拍摄风景图像的中间部分和用于肖像图像的顶部。 所以这是一种标准行为。 然后它调整裁剪图像的大小(它已经是一个正方形)。

这段代码好吗? 会更快吗? 怎么样? 任何可能的优化?

你的日常工作很好但是有一个小问题,至少在我想要的应用中。 我希望例程能够像处理横向位图一样裁剪肖像位图; 通过从位图的顶部和一半多余部分裁掉一半的多余部分。 所以我只是将横向裁剪代码复制到肖像裁剪代码并根据需要进行调整,结果如下:

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