Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Bitmap into other Bitmap with WPF

Tags:

image

bitmap

wpf

I need to put a bitmap into the center of another bitmap with WPF.

I managed to create a empty picture with the dimensions I want but I don't understand how to copy another BitmapFrame into it.

BitmapSource bs = BitmapSource.Create(
    width, height,
    dpi, dpi,
    PixelFormats.Rgb24,
    null,
    bits,
    stride);
like image 723
martinyyyy Avatar asked Feb 21 '26 01:02

martinyyyy


1 Answers

You should use WriteableBitmap, to write to the Pixel buffer. Copying from BitmapSource to an array using BitmapSource.CopyPixels, then copy the array to the WriteableBitmap using WriteableBitmap.WritePixels.

Here is a commented implementation

XAML

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

Code

// 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;
like image 61
Chris Taylor Avatar answered Feb 25 '26 09:02

Chris Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!