功能描述
“调整图像大小”
将传入的图像拉伸或压缩到指定的宽高。
“调整画布大小”
将传入的图像的背景扩展或裁切到指定的宽高。 在这一过程中,原图像居中且大小不会改变。 拓展的部分会被自动设为透明底,有需要请自行添加.Clear(Color.White);代码。
功能代码
internal class MyImageProcesser
{
///
/// 调整图像大小
///
/// 要调整的图像
/// 目标宽度
/// 目标高度
public static Image AdjustGraphic(Image image, double targetWidth, double targetHeight)
{
if (image.Width == targetWidth && image.Height == targetHeight)
{
return image;
}
else
{
double newWidth = targetWidth;
double newHeight = targetHeight;
Image newImage = new Bitmap((int)newWidth, (int)newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
g.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
}
return newImage;
}
}
///
/// 调整画布大小
///
/// 要调整的图像
/// 目标宽度
/// 目标高度
public static Image AdjustPainter(Image image, double targetWidth, double targetHeight)
{
double newWidth = targetWidth;
double newHeight = targetHeight;
Bitmap newCanvas = new Bitmap((int)newWidth, (int)newHeight);
// 计算原始图像在新画布中的居中位置
int x = (int)((newWidth - image.Width) / 2);
int y = (int)((newHeight - image.Height) / 2);
using (Graphics g = Graphics.FromImage(newCanvas))
{
// 将原始图像绘制到新画布的居中位置
g.DrawImage(image, x, y, image.Width, image.Height);
}
return newCanvas;
}
}
调用示例
var image = Image.FromFile("...");
// 将图像的画布大小调整为 300,200
image = MyImageProcesser.AdjustPainter(image, 300, 200);
// 将图像的图像大小调整为 150,100
image = MyImageProcesser.AdjustGraphic(image, 150, 100);
|