簡體   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