[英]Graphics.DrawImage not changing size of image
我有一个功能,可以获取图像并调整其大小以适合画布,同时保持其纵横比。 此代码只是此答案中代码的略微修改版本: c#在保留纵横比的同时将图像调整为不同大小
对于此示例,我的画布高度为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;
}
图片的尺寸在这里定义
Image image = (Bitmap)workingImage.Clone();
这个
graphic.DrawImage(image, posX, posY, newWidth, newHeight);
仅使用指定的参数绘制图像,但这并不意味着图像大小被更改。 换句话说,绘制图像根本不会改变其大小,它只是获取图像并将其按照您的意愿绘制在画布上。
图像调整大小功能,请参见以下链接
此链接内容可能对您有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.