2011-10-18 103 views
4

我有想要傳入Excel單元格(通過剪貼板緩衝區)的3D WPF可視化。將RenderTargetBitmap轉換爲System.Drawing.Image

與「正常」BMP圖像的作品,但我不知道如何轉換RenderTargetBitmap

我的代碼如下所示:

System.Windows.Media.Imaging.RenderTargetBitmap renderTarget = myParent.GetViewPortAsImage(DiagramSizeX, DiagramSizeY); 
System.Windows.Controls.Image myImage = new System.Windows.Controls.Image(); 
myImage.Source = renderTarget; 

System.Drawing.Bitmap pg = new System.Drawing.Bitmap(DiagramSizeX, DiagramSizeY); 
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(pg); 
gr.DrawImage(myImage, 0, 0); 

System.Windows.Forms.Clipboard.SetDataObject(pg, true); 
sheet.Paste(range); 

我的問題是gr.DrawImage不接受System.Windows.Controls.ImageSystem.Windows.Media.Imaging.RenderTargetBitmap;只有一個System.Drawing.Image

如何將Controls.Image.Imaging.RenderTargetBitmap轉換爲Image或者有沒有更簡單的方法?

回答

2

這是我想出了

System.Windows.Media.Imaging.RenderTargetBitmap renderTarget = myParent.GetViewPortAsImage(DiagramSizeX, DiagramSizeY); 
System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); 
MemoryStream myStream = new MemoryStream(); 

encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(renderTarget)); 
encoder.Save(myStream); 
// 
System.Drawing.Bitmap pg = new System.Drawing.Bitmap(DiagramSizeX, DiagramSizeY); 
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(pg); 
// 
// Background 
// 
gr.FillRectangle(new System.Drawing.SolidBrush(BKGC), 0, 0, DiagramSizeX, DiagramSizeY); 
// 
gr.DrawImage(System.Drawing.Bitmap.FromStream(myStream), 0, 0); 
System.Windows.Forms.Clipboard.SetDataObject(pg, true); 

sheet.Paste(range); 
0

也許解決方案,我不明白的問題的權利,但你要一個RenderTargetBitmap複製到剪貼板,不能你剛纔叫SetImage:

Dim iRT As RenderTargetBitmap = makeImage() //this is what you do to get the rendertargetbitmap 
    If iRT Is Nothing Then Exit Sub 
    Clipboard.SetImage(iRT) 
2

您可以將RenderTargetBitmap中的像素直接複製到新的Bitmap的像素緩衝區中。請注意,我假設您的RenderTargetBitmap使用PixelFormats.Pbrga32,因爲任何其他像素格式的使用都會從RenderTargetBitmap的構造函數中拋出異常。

var bitmap = new Bitmap(renderTarget.PixelWidth, renderTarget.PixelHeight, 
    PixelFormat.Format32bppPArgb); 

var bitmapData = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), 
    ImageLockMode.WriteOnly, bitmap.PixelFormat); 

renderTarget.CopyPixels(Int32Rect.Empty, bitmapData.Scan0, 
    bitmapData.Stride*bitmapData.Height, bitmapData.Stride); 

bitmap.UnlockBits(bitmapData); 
相關問題