C#代码实现模拟Photoshop“调整图像大小”和“调整画布大小”功能

您所在的位置:网站首页 photoshop图片尺寸打印尺寸 C#代码实现模拟Photoshop“调整图像大小”和“调整画布大小”功能

C#代码实现模拟Photoshop“调整图像大小”和“调整画布大小”功能

2023-07-03 05:45| 来源: 网络整理| 查看: 265

功能描述 “调整图像大小”

将传入的图像拉伸或压缩到指定的宽高。

“调整画布大小”

将传入的图像的背景扩展或裁切到指定的宽高。 在这一过程中,原图像居中且大小不会改变。 拓展的部分会被自动设为透明底,有需要请自行添加.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);


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3