gul*_*aek 6 .net c# wpf c#-4.0
这是关于在WPF应用程序中将图像保存到文件保持宽高比的后续问题
我知道如何缩放图像,但如何扩展画布大小,以确保图像仍然具有所需的宽度和高度.在这个例子中它的250x250但它的动态.
我创建了这个插图来展示我想要帮助的东西.

我找不到任何方法来扩展BitmapImage的画布,也没有办法以正确的大小创建内存图像,使用透明背景,然后将两个图像合并在一起.
Kri*_*is 6
CroppedBitmap似乎不支持在图像周围添加空间,因此您可以使用WriteableBitmap创建正确大小的透明图像.如果输入小于目标大小,则此方法会将其放大,但这很容易改变.
public static BitmapSource FitImage(BitmapSource input, int width, int height)
{
if (input.PixelWidth == width && input.PixelHeight == height)
return input;
if(input.Format != PixelFormats.Bgra32 || input.Format != PixelFormats.Pbgra32)
input = new FormatConvertedBitmap(input, PixelFormats.Bgra32, null, 0);
//Use the same scale for x and y to keep aspect ratio.
double scale = Math.Min((double)width / input.PixelWidth, height / (double)input.PixelHeight);
int x = (int)Math.Round((width - (input.PixelWidth * scale))/2);
int y = (int)Math.Round((height - (input.PixelHeight * scale))/2);
var scaled = new TransformedBitmap(input, new ScaleTransform(scale, scale));
var stride = scaled.PixelWidth * (scaled.Format.BitsPerPixel / 8);
var result = new WriteableBitmap(width, height, input.DpiX, input.DpiY, input.Format,null);
var data = new byte[scaled.PixelHeight * stride];
scaled.CopyPixels(data, stride, 0);
result.WritePixels(new Int32Rect(0,0,scaled.PixelWidth,scaled.PixelHeight), data, stride,x,y);
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果您已经使用RenderTargetBitmap渲染内容,则可以将其包装在ViewBox中进行缩放,但如果您只使用普通图像,我将使用上述方法.