在WPF应用程序中展开BitmapImage中的canvas/透明背景

这是关于在WPF应用程序中将图像保存到文件保持宽高比的后续问题

我知道如何缩放图像,但如何扩展canvas大小,以确保图像仍然具有所需的宽度和高度。 在这个例子中它的250×250但它的动态。

我创建了这个插图来展示我想要帮助的东西。 替代文字

我找不到任何方法来扩展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中进行缩放,但如果您只使用普通图像,我将使用上述方法。

您应该能够将Stretch属性设置为Uniform。

只是一些代码,以防其他人试图从表单上传后处理文件。

 if (file.PostedFile != null) { //write the new file to disk string cachePath = String.Format("{0}temp\\", Request.PhysicalApplicationPath); string photoPath = String.Format("{0}temp.png", cachePath); if (!Directory.Exists(cachePath)) { Directory.CreateDirectory(cachePath); } file.PostedFile.SaveAs(photoPath); //resize the new file and save it to disk BitmapSource banana = FitImage(ReadBitmapFrame(file.PostedFile.InputStream), 640, 480); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(banana)); FileStream pngStream = new FileStream(cachePath + "test.png", FileMode.Create); encoder.Save(pngStream); pngStream.Close(); //set a couple images on page to the newly uploaded and newly processed files image.Src = "temp/temp.png"; image.Visible = true; image2.Src = "temp/test.png"; image2.Visible = true; }