Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to resample an image to square, padding with white background in c# preferable without using any 3rd party libraries (.Net framework only)?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
130 views
Welcome To Ask or Share your Answers For Others

1 Answer

This can actually be done pretty easily.

public static Image PadImage(Image originalImage)
{
    int largestDimension = Math.Max(originalImage.Height, originalImage.Width);
    Size squareSize = new Size(largestDimension, largestDimension);
    Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height);
    using (Graphics graphics = Graphics.FromImage(squareImage))
    {
        graphics.FillRectangle(Brushes.White, 0, 0, squareSize.Width, squareSize.Height);
        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        graphics.DrawImage(originalImage, (squareSize.Width / 2) - (originalImage.Width / 2), (squareSize.Height / 2) - (originalImage.Height / 2), originalImage.Width, originalImage.Height);
    }
    return squareImage;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...