Skip to content

Instantly share code, notes, and snippets.

@kuroneko0441
Last active March 22, 2021 01:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuroneko0441/0e5d6ced364e38e932e746bb4e0bf87f to your computer and use it in GitHub Desktop.
Save kuroneko0441/0e5d6ced364e38e932e746bb4e0bf87f to your computer and use it in GitHub Desktop.
C# 이미지 리사이즈(비율 유지)
using System;
using System.Drawing;
namespace ImageConvertor {
class ImageConvertor {
/**
* <summary>
* 이미지를 targetX, targetY로 리사이징함. 비율은 유지하고 빈 공간은 검은색으로 채움
* </summary>
*/
public static void Resize(string importPath, string exportPath, int targetX, int targetY) {
Image originalImage = Image.FromFile(importPath);
double ratioX = targetX / (double)originalImage.Width;
double ratioY = targetY / (double)originalImage.Height;
double ratio = Math.Min(ratioX, ratioY);
int newWidth = (int)(originalImage.Width * ratio);
int newHeight = (int)(originalImage.Height * ratio);
Bitmap newImage = new Bitmap(targetX, targetY);
using (Graphics g = Graphics.FromImage(newImage)) {
g.FillRectangle(Brushes.Black, 0, 0, newImage.Width, newImage.Height);
g.DrawImage(originalImage, (targetX - newWidth) / 2, (targetY - newHeight) / 2, newWidth, newHeight);
}
newImage.Save(exportPath);
originalImage.Dispose();
newImage.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment