我有一个函数,它接收图像并调整其大小以适应画布,同时保持其纵横比。这个代码只是这个答案的代码的一个小修改版本:c#在保留纵横比的同时将图像调整为不同的大小
对于这个例子,我的画布高度是642,画布宽度是823。
当我运行以下功能时,行
graphic.DrawImage(image, posX, posY, newWidth, newHeight);
似乎对图像大小没有任何影响。进入:
Image.Height == 800,
Image.Width == 1280.
newHeight = 514,
newWidth == 823
运行图形后。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;
}
此处定义图像的大小
Image image = (Bitmap)workingImage.Clone();
这个
graphic.DrawImage(image, posX, posY, newWidth, newHeight);
仅使用指定的参数绘制图像,但这并不意味着图像大小会发生更改。换句话说,绘制图像并不会改变其大小,它只是根据您的意愿将图像绘制在画布上。
图像大小调整功能参见以下链接
http://www.codeproject.com/Articles/30524/An-Easy-to-Use-Image-Resizing-and-Cropping-Control?msg=5203911#xx5203911xx
此链接内容可能有助于您