반응형
public static bool ResizeImageFile(string imageFilePath, in int newWidth, in int newHeight, in bool keepSizeRatio = true)
{
try
{
byte[] byteArr = File.ReadAllBytes(imageFilePath);
using (var stream = new System.IO.MemoryStream(byteArr))
{
Bitmap bitmap = new Bitmap(stream);
int applyWidth = newWidth;
int applyHeight = newHeight;
if (keepSizeRatio)
{
double percentW = 0;
double percentH = 0;
double targetPercent = 0;
percentW = (double)newWidth / bitmap.Width;
percentH = (double)newHeight / bitmap.Height;
if (percentW < percentH) targetPercent = percentW;
else targetPercent = percentH;
applyWidth = (int)(bitmap.Width * targetPercent);
applyHeight = (int)(bitmap.Height * targetPercent);
if (applyWidth > newWidth) applyWidth = newWidth;
if (applyHeight > newHeight) applyHeight = newHeight;
}
bitmap = ResizeImage(bitmap, applyWidth, applyHeight);
bitmap.Save(imageFilePath);
bitmap.Dispose();
}
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
}
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
반응형
'[====== Development ======] > C#' 카테고리의 다른 글
C# Deserialize JSON into SQLite Database (0) | 2022.06.18 |
---|---|
Expression-bodied member (0) | 2022.06.14 |
[C#] 이미지 크기 변경하기 (0) | 2022.06.08 |
fo-dicom Load , Save 한글 깨짐 문제점 해결 (0) | 2022.06.05 |
File을 Base64String으로 읽어오기 (0) | 2022.06.03 |