我有一个功能,它可以接收图像并调整大小以适应画布,同时保持其宽高比。此代码只是此答案的代码的少量修改版本:c# Image resizing to different size while preserving aspect ratio
对于此示例,我的画布高度为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.
如您所见,Image的高度和宽度不变。
有没有人看到会导致这种情况发生的明显错误?谢谢!
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;
}
答案 0 :(得分:5)
图片大小在此处定义
Image image = (Bitmap)workingImage.Clone();
此
graphic.DrawImage(image, posX, posY, newWidth, newHeight);
仅使用指定的参数绘制图像,但这并不意味着图像大小会发生变化。换句话说,绘制图像根本不会改变它的大小,它只是拍摄图像并将其绘制在画布上。
答案 1 :(得分:0)
Image Resizing functanality pupose请参阅以下链接
此链接内容可能会对您有所帮助