Copying from BitmapSource to WritableBitmap

后端 未结 1 1624
予麋鹿
予麋鹿 2021-02-15 03:48

I am trying to copy a part of a BitmapSource to a WritableBitmap.

This is my code so far:

var bmp = image.Source as BitmapSource;
var row = new Writeable         


        
1条回答
  •  无人及你
    2021-02-15 04:24

    What part of the image are trying to copy? change the width and height in the target ctor, and the width and height in Int32Rect as well as the first two params (0,0) which are x & y offsets into the image. Or just leave if you want to copy the whole thing.

    BitmapSource source = sourceImage.Source as BitmapSource;
    
    // Calculate stride of source
    int stride = source.PixelWidth * (source.Format.BitsPerPixel + 7) / 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  element 
    // in XAML so you can see the result of the copy
    targetImage.Source = target;
    

    0 讨论(0)
提交回复
热议问题