简体   繁体   English

WPF:如何从另一个BitmapImage创建一个BitmapImage…?

[英]WPF: How to create a BitmapImage… from another BitmapImage?

I have a method where I accept as a parameter a BitmapImage that is small say 25x25 我有一个方法,我接受一个很小的BitmapImage作为参数,例如25x25

public BitmapImage MakeLargerAndAddBorder(BitmapImage smallImage)
{
   ...
}

I'd like this method to return a bigger image say 50x50, that programmatically puts the smaller image in the middle (doesn't scale or change this smallerImage mind you), gives it a background color, and slaps a white border on it. 我希望此方法返回较大的图像(例如50x50),以编程方式将较小的图像置于中间(请注意,您不会缩放或更改此smallImage),为其提供背景颜色,并在其上打上白色边框。 I'm wondering if this is even possible? 我想知道这是否有可能? It's a long story but I don't have the URL to the image, just an existing BitmapImage object... I'm wondering if I can somehow programmatically convert this to a larger image? 这是一个很长的故事,但是我没有图像的URL,只有一个现有的BitmapImage对象...我想知道是否可以以编程方式将其转换为更大的图像? I've been googling for this but I can't really find a way to programmatically create a BitmapImage. 我一直在为此搜索,但是我真的找不到一种以编程方式创建BitmapImage的方法。 (esp from an existing one) (特别是现有的)

You want WriteableBitmap. 您需要WriteableBitmap。 :) Just create a WriteableBitmap with the same parameters as your original (with the modified size). :)只需创建一个与原始参数相同的WriteableBitmap(大小已更改)。 Then lock the bitmap and use its BackBuffer property to access the underlying pixels. 然后锁定位图,并使用其BackBuffer属性访问基础像素。 You should be able to use the CopyPixels() method to copy the original image into your new one. 您应该能够使用CopyPixels()方法将原始图像复制到新图像中。

Here is an example of how to do this in XAML with a bit of code-behind. 这是一个如何在XAML中执行此操作的示例,并附带一些代码。

<Border Width="50" Height="50" BorderThickness="2" BorderBrush="Black">
  <Image x:Name="myImage" Height="25" 
                          Width="25"/>
</Border>

In the code behind, if you can not provide a Source URL (which you have said you can't), you can set the source property of the Image control. 在后面的代码中,如果您不能提供Source URL(您说过不能),则可以设置Image控件的source属性。

myImage.Source = bitmap; // your bitmap object.

If you do not set the size on your Image and Border in the XAML, they should expand to whatever size is required. 如果未在XAML中的“图像和边框”上设置大小,则它们应扩展为所需的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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