[英]Image Getting Stretched when trying to Resize It keeping the aspect Ratio
我使用以下代碼來調整圖像的大小,以保留寬高比
public Bitmap resizeImage(System.Drawing.Image imgToResize, SizeF size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
// Used to Prevent White Line Border
// g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return b;
}
但是大寬度的圖像會被壓縮,內容似乎被壓縮在一個很小的空間中。我要達到的目的是: 調整大尺寸/大分辨率圖像的尺寸,因為處理此過程將花費大量時間,因此當圖像的寬度或高度超過說1000我想將圖像調整為較小的尺寸,例如:1000寬度或高度較大,這樣我可以節省計算時間。但是,似乎上面的代碼是在我試圖將圖像適合1000X1000 Box時強行嘗試做
if (y.Width > 1000 || y.Height > 1000)
{
y = new Bitmap( resizeImage(y, new Size(1000, 1000)));
}
試試這個,有點整潔
public static Bitmap ResizeImage(Bitmap source, Size size)
{
var scale = Math.Min(size.Width / (double)source.Width, size.Height / (double)source.Height);
var bmp = new Bitmap((int)(source.Width * scale), (int)(source.Height * scale));
using (var graph = Graphics.FromImage(bmp))
{
graph.InterpolationMode = InterpolationMode.High;
graph.CompositingQuality = CompositingQuality.HighQuality;
graph.SmoothingMode = SmoothingMode.AntiAlias;
graph.DrawImage(source, 0, 0, bmp.Width, bmp.Height);
}
return bmp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.