简体   繁体   中英

Save Image to file keeping aspect ratio in a WPF app

Hi I trying to scale a png image with a transparent background. I need it to be 250x250 pixel.

Horizontal and vertical centered and keeping the correct aspect ration. The possibility to set a margin.

This is what I got so far.

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();

I know that its not using the Image object yet, and therefor just saves the image without scaling it. But I'm having trouble saving the Image object. It gives a compile error of cannot convert from 'System.Windows.Controls.Image' to 'System.Uri'

Hope someone can help me :-)

EDIT

Updated the code, to the version with the compile error. just changed

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

to

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

And here is a list of my using

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;

What you're doing is similar to zooming in an editor on an image and expecting it to be reflected in the underlying image when you save. What you'll need to do is create a TransformedBitmap to modify the image and then add that to the Frames. eg

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

Update Regarding the aspect Ratio.

I need it to be 250x250 pixel

If the source image doesn't have a 1:1 ratio for height and width the scaling above meets the "I need it be 250X250" but will create distortion.

To get around this you'll need to either crop the image or scale the image so that just one dimension is 250 pixels.

To crop the image you can either use the Clip Property or a CroppedBitmap . To scale just one dimension you just use one dimension to determine the scale eg new ScaleTransform(250 / bi.Width, 250 / bi.width);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM