c# - 在 WPF 应用程序的 BitmapImage 中展开 Canvas /透明背景

标签 c# .net wpf c#-4.0

这是关于 Save image to file keeping aspect ration in a WPF app 的后续问题

我知道如何缩放图像,但如何扩展 Canvas 大小,以确保图像仍然具有请求的宽度和高度。在此示例中,它是 250x250,但它是动态的。

我创建了这个插图来展示我正在努力实现的目标。 alt text

我找不到任何方法来扩展 BitmapImage 的 Canvas ,也找不到在内存中创建大小正确、背景透明的图像,然后将两个图像合并在一起的方法。

最佳答案

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;
}

如果您已经在使用 RenderTargetBitmap 渲染内容,您可以将其包装在 ViewBox 中以进行缩放,但如果您只是处理普通图像,我会使用上述方法。

关于c# - 在 WPF 应用程序的 BitmapImage 中展开 Canvas /透明背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681084/

相关文章:

c# - 获取当前类名包括父类名?

c# - Xamarin Studio 和项目引用

c# - jqgrid动态格式化列

c# - 为什么 .NET 在 String.Format 中使用与默认 Math.Round() 算法不一致的舍入算法?

wpf - 在 WPF 应用程序中将按钮大小设置为内容大小

C# 屏蔽数组以排除索引,速度与 Python 一样快

c# - 您可以为每个 SendEndpoint 定义 UseRawJsonSerializer() 吗?

.net - 包装 IQueryable

c# - Devenv Commandline Build 不使用 C# 7.2 语言功能

c# - WPF 单实例最佳实践