2010-06-04 18 views
4

我試圖從我的WPF應用程序的一部分創建一個JPG。像截圖一樣,只有個人UIElement s。我從這裏開始:http://www.grumpydev.com/2009/01/03/taking-wpf-screenshots/從UIElement使用C的WPF屏幕截圖JPG#

我使用他的擴展方法,它基本上允許你得到一個字節[]與UIElement.GetJpgImage()。這可以使用文件流寫入JPG圖像。如果我把整個窗口做成JPG,看起來就好!但是,這並不理想,因爲它只是捕捉用戶看到的內容。由於scrollviewer或者因爲他們的父項被動畫成小尺寸而看不見的東西不會顯示出來。

如果我需要的,比如說「截圖」,我使用的佈局網格: alt text http://img697.imageshack.us/img697/4233/fullscreenshot2.jpg

我這爛東西,背景爲黑色。我不想那樣。此外,如果我使用動畫摺疊了這個網格的高度,我什麼也得不到。這些實際上是模板化的複選框,它們上面應該有黑色文本,並且網格的背景應該是白色的。下面是別人寫的返回被寫入到文件流的byte []數組代碼:

public static byte[] GetJpgImage(this UIElement source, double scale, int quality) 
{ 
    double actualHeight = source.RenderSize.Height; 
    double actualWidth = source.RenderSize.Width; 

    double renderHeight = actualHeight * scale; 
    double renderWidth = actualWidth * scale; 

    RenderTargetBitmap renderTarget = new RenderTargetBitmap((int) renderWidth, (int) renderHeight, 96, 96, PixelFormats.Pbgra32); 
    VisualBrush sourceBrush = new VisualBrush(source); 

    DrawingVisual drawingVisual = new DrawingVisual(); 
    DrawingContext drawingContext = drawingVisual.RenderOpen(); 

    using (drawingContext) 
    { 
     drawingContext.PushTransform(new ScaleTransform(scale, scale)); 
     drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); 
    } 
    renderTarget.Render(drawingVisual); 

    JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder(); 
    jpgEncoder.QualityLevel = quality; 
    jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget)); 

    Byte[] _imageArray; 

    using (MemoryStream outputStream = new MemoryStream()) 
    { 
     jpgEncoder.Save(outputStream); 
     _imageArray = outputStream.ToArray(); 
    } 

    return _imageArray; 
} 

某處在那裏,我們得到一個黑色的背景。任何見解?

編輯:如果我將網格的背景屬性設置爲白色,屏幕截圖按預期顯示。但是,設置我需要截取的所有背景是不可行的。

回答

5

只是一個猜測,我會認爲黑色背景將代表字節數組的一部分,在這個過程中沒有設置任何東西。數組中的初始零將顯示爲黑色。

爲了避免這種情況,我建議用0xFF(byte.MaxValue)值初始化數組。

更新:

從這個仔細一看,我認爲你應該畫一個白色矩形到圖像渲染UI元素之前。無論如何,這應該工作。

就在這行代碼

drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); 

把類似的東西的工作只是設置元素在XAML背景這

drawingContext.DrawRectangle(Brushes.White, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); 
+0

當「_imageArray = outputStream.ToArray();」填充數組時,我該怎麼做? – 2010-06-04 20:09:23

+0

我認爲這不僅僅是黑色,它可能是透明的黑色(可以通過保存到PNG快速檢查)。因此,您可以在所需背景上繪製圖像並保存最終圖像。 – max 2010-06-04 20:14:59

+0

如果@max所暗示的是透明黑色,那麼您可以掃描字節數組,設置alpha通道中每個像素的顏色爲零。 – 2010-06-04 20:22:03

0

不幸的是,唯一的事情。我不想這樣做,但我想這是我在這種情況下需要做的。無論如何感謝您的建議。