使用WPF将位图复制到另一个位图中

3

我需要在WPF中将一个位图放置在另一个位图的中心。

我已经成功创建了一个具有所需尺寸的空白图片,但我不知道如何将另一个BitmapFrame复制到其中。

BitmapSource bs = BitmapSource.Create(
    width, height,
    dpi, dpi,
    PixelFormats.Rgb24,
    null,
    bits,
    stride);
1个回答

7

您应该使用WriteableBitmap来写入像素缓冲区。使用BitmapSource.CopyPixels从BitmapSource复制到数组,然后使用WriteableBitmap.WritePixels将数组复制到WriteableBitmap中。

这里是一个有注释的实现

XAML

<Image Name="sourceImage" Height="50"
       Source="/WpfApplication1;component/Images/Gravitar.bmp" />
<Image Name="targetImage" Height="50"/>

代码

// Quick and dirty, get the BitmapSource from an existing <Image> element
// in the XAML
BitmapSource source = sourceImage.Source as BitmapSource;

// Calculate stride of source
int stride = source.PixelWidth * (source.Format.BitsPerPixel / 8);

// Create data array to hold source pixel data
byte[] data = new byte[stride * source.PixelHeight];

// Copy source image pixels to the data array
source.CopyPixels(data, stride, 0);

// Create WriteableBitmap to copy the pixel data to.      
WriteableBitmap target = new WriteableBitmap(
  source.PixelWidth, 
  source.PixelHeight, 
  source.DpiX, source.DpiY, 
  source.Format, null);

// Write the pixel data to the WriteableBitmap.
target.WritePixels(
  new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight), 
  data, stride, 0);

// Set the WriteableBitmap as the source for the <Image> element 
// in XAML so you can see the result of the copy
targetImage.Source = target;

你所编写的 WritePixels 调用没有匹配到任何重载。 - nrofis
@nrofis,我现在没有VS在面前,但文档显示了特定的重载 https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.imaging.writeablebitmap.writepixels?view=netframework-4.7#System_Windows_Media_Imaging_WriteableBitmap_WritePixels_System_Windows_Int32Rect_System_Array_System_Int32_System_Int32_ - Chris Taylor
抱歉,我的错! - nrofis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接