winform bitmap缩放为指定尺寸
时间: 2024-11-15 07:34:43 浏览: 45
在Windows Forms中,如果你想将Bitmap图像缩放到特定尺寸,你可以使用`Graphics`类的`DrawImage`方法结合`ScaleTransform`。以下是一个简单的步骤:
1. 创建Bitmap对象并加载原始图像资源:
```csharp
Bitmap originalBitmap = new Bitmap("original_image_path.jpg");
```
2. 使用Graphics对象,并创建一个绘图区域的大小,即目标尺寸:
```csharp
int targetWidth = desiredWidth;
int targetHeight = desiredHeight;
Graphics g = Graphics.FromImage(new Bitmap(targetWidth, targetHeight));
```
注意这里的`desiredWidth`和`desiredHeight`是你想要的新宽度和高度。
3. 设置缩放比例:
```csharp
double scaleRatioX = (double)targetWidth / originalBitmap.Width;
double scaleRatioY = (double)targetHeight / originalBitmap.Height;
// 确保保持图片长宽比
if (scaleRatioX != scaleRatioY)
{
double ratio = Math.Min(scaleRatioX, scaleRatioY);
scaleRatioX = ratio;
scaleRatioY = ratio;
}
```
4. 缩放和绘制图像:
```csharp
g.DrawImage(originalBitmap, new Rectangle(0, 0, targetWidth, targetHeight), 0, 0, originalBitmap.Width, originalBitmap.Height, GraphicsUnit.Pixel, new ImageAttributes { InterpolationMode = InterpolationMode.HighQualityBicubic });
```
这里使用了`InterpolationMode.HighQualityBicubic`来保证缩放过程中的平滑过渡。
5. 最后,你可以选择是否保存这个新的缩略图:
```csharp
originalBitmap.Save("scaled_image_path.jpg", ImageFormat.Jpeg);
```
阅读全文
相关推荐


















