将图像保存到WPF应用程序中的文件保持宽高比

嗨,我试图用透明背景缩放png图像。 我需要它是250×250像素。

水平和垂直居中并保持正确的纵横比。 设定保证金的可能性。

这是我到目前为止所得到的。

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对象,因此只保存图像而不缩放它。 但是我在保存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; 

你正在做的是类似于放大图像上的编辑器并期望它在保存时反映在底层图像中。 您需要做的是创建一个TransformedBitmap来修改图像,然后将其添加到Frames。 例如

  var scale = new ScaleTransform(250 / bi.Width, 250 / bi.Height); var tb = new TransformedBitmap(bi, scale); pngBitmapEncoder.Frames.Add( BitmapFrame.Create(tb)); 

关于宽高比的更新

我需要它是250×250像素

如果源图像的高度和宽度比率不是1:1,则上面的缩放符合“我需要它是250X250”,但会产生失真。

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

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