2010-11-07 54 views
2

我需要使用WPF將位圖放入另一個位圖的中心。使用WPF將位圖複製到其他位圖

我設法用我想要的尺寸創建一張空白圖片,但我不明白如何將其他BitmapFrame複製到它。

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

回答

6

您應該使用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; 
+0

沒有超載與您寫的WritePixels調用匹配。 – nrofis 2017-12-12 10:23:32

+0

@nrofis,我現在沒有VS在我面前,但文檔顯示特定的重載https://docs.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_ – 2017-12-13 05:38:04

+0

對不起,我的錯! – nrofis 2017-12-13 09:48:17