我有一個函數,它可以接受圖像並調整它的大小以適合畫布,同時保持其縱橫比。此代碼只能從這個答案代碼的minorly修改後的版本:c# Image resizing to different size while preserving aspect ratioGraphics.DrawImage不改變圖像的大小
在這個例子中,我的畫布高度是642,我的畫布寬度爲823
當我運行下面的功能,線路
graphic.DrawImage(image, posX, posY, newWidth, newHeight);
貌似對圖像大小沒有影響。在場地狀況:
Image.Height == 800,
Image.Width == 1280.
newHeight = 514,
newWidth == 823
運行後graphic.DrawImage
Image.Height == 800,
Image.Width == 1280.
正如你所看到的,圖像的高度和寬度都不變。
有沒有人看到一個明顯的錯誤會導致這種情況發生?謝謝!
private Bitmap resizeImage(Bitmap workingImage,
int canvasWidth, int canvasHeight)
{
Image image = (Bitmap)workingImage.Clone();
System.Drawing.Image thumbnail =
new Bitmap(canvasWidth, canvasHeight);
double ratioX = (double)canvasWidth/(double)workingImage.Width;
double ratioY = (double)canvasHeight/(double)workingImage.Height;
double ratio = ratioX < ratioY ? ratioX : ratioY;
int newHeight = Convert.ToInt32((double)workingImage.Height * ratio);
int newWidth = Convert.ToInt32((double)workingImage.Width * ratio);
int posX = Convert.ToInt32((canvasWidth - ((double)workingImage.Width * ratio))/2);
int posY = Convert.ToInt32((canvasHeight - ((double)workingImage.Height * ratio))/2);
using (Graphics graphic = Graphics.FromImage(thumbnail))
{
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphic.Clear(SystemColors.Control);
graphic.DrawImage(image, posX, posY, newWidth, newHeight); //<--- HERE
}
System.Drawing.Imaging.ImageCodecInfo[] info =
System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
System.Drawing.Imaging.EncoderParameters encoderParameters;
encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
100L);
return workingImage;
}
我覺得POSX和波西應該是兩個0 - 你開始新鮮的,所以你要填補整個地區。縮略圖應該使用新的尺寸創建,而不是原始的(不是canvasW和canvasH)。 – pasty