我試圖從我的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;
}
某處在那裏,我們得到一個黑色的背景。任何見解?
編輯:如果我將網格的背景屬性設置爲白色,屏幕截圖按預期顯示。但是,設置我需要截取的所有背景是不可行的。
當「_imageArray = outputStream.ToArray();」填充數組時,我該怎麼做? – 2010-06-04 20:09:23
我認爲這不僅僅是黑色,它可能是透明的黑色(可以通過保存到PNG快速檢查)。因此,您可以在所需背景上繪製圖像並保存最終圖像。 – max 2010-06-04 20:14:59
如果@max所暗示的是透明黑色,那麼您可以掃描字節數組,設置alpha通道中每個像素的顏色爲零。 – 2010-06-04 20:22:03