在WPF应用程序中保持纵横比保存图像到文件

3

你好,我正在尝试对带有透明背景的PNG图像进行缩放。我需要它变成250x250像素。

水平和垂直居中,并保持正确的纵横比。可以设置边距。

目前为止,这就是我得到的。

var img = new System.Windows.Controls.Image();
var bi = new BitmapImage(new Uri("C://tmp/original.png", UriKind.RelativeOrAbsolute));
img.Stretch = Stretch.Uniform;
img.Width = 250;
img.Height = 250;
img.Source = bi;

var pngBitmapEncoder = new PngBitmapEncoder();

var stream = new FileStream("C://tmp/test3.png", FileMode.Create);

pngBitmapEncoder.Frames.Add(BitmapFrame.Create(img));
pngBitmapEncoder.Save(stream);
stream.Close();

我知道它还没有使用 Image 对象,因此只是保存图像而不进行缩放。但是我无法保存图像对象。它会出现编译错误,指出无法将“System.Windows.Controls.Image”转换为“System.Uri”。 希望有人能帮助我 :-) 编辑 更新了代码,出现编译错误的版本。只是进行了更改
pngBitmapEncoder.Frames.Add(BitmapFrame.Create(bi));

为了

pngBitmapEncoder.Frames.Add(BitmapFrame.Create(img));

以下是我使用的列表:
using System;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Image = System.Windows.Controls.Image;

也许可以展示一下出现错误的代码?而不是解决方法。 - H H
可能是由于@fullfilename的问题。请检查fullfilename中的值。这段代码在我的电脑上运行良好。 - Binil
他指出,那段代码只保存了原始图像而没有缩放后的图片。 - H.B.
1个回答

3
你所做的类似于在编辑器中放大图像,并期望在保存时反映在底层图像上。你需要创建一个TransformedBitmap来修改图像,然后将其添加到帧中。例如:
        var scale = new ScaleTransform(250 / bi.Width, 250 / bi.Height);
        var tb = new TransformedBitmap(bi, scale);
        pngBitmapEncoder.Frames.Add( BitmapFrame.Create(tb));

更新 关于宽高比的问题。

我需要它是250x250像素。

如果源图像的高度和宽度没有1:1的比例,则上述缩放可以满足“我需要它是250X250”,但会产生失真。

要解决这个问题,您需要裁剪图像或缩放图像,使只有一个维度为250像素。

要裁剪图像,您可以使用Clip PropertyCroppedBitmap。要仅缩放一个维度,您只需使用一个维度来确定缩放,例如 new ScaleTransform(250 / bi.Width, 250 / bi.width);


谢谢您的建议,但是当尝试保持纵横比时,如果输入图像与输出图像不具有相同的纵横比,则会出现问题。我会更新我的问题,使其更加清晰明了。 - gulbaek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接