2013-04-07 25 views
1

如何將Gdk.Pixbuf(_pixbuf在下面)轉換爲Windows窗體(System.Drawing)位圖?以下是使用Gtk.DotNet.Graphics的代碼,但它僅顯示白色圖像。有更好,更直接的方法嗎?我在Mono上使用C#,但如果你有其他語言的答案,我可以轉換。將Gdk.Pixbuf轉換爲System.Drawing.Bitmap?

public System.Drawing.Bitmap toBitmap() { 
    Gdk.Pixmap pixmap, mask; 
    _pixbuf.RenderPixmapAndMask(out pixmap, out mask, 255); 
    System.Drawing.Graphics graphics = Gtk.DotNet.Graphics.FromDrawable(pixmap); 
    return new System.Drawing.Bitmap(width, height, graphics); 
} 

回答

2

您可以使用此方法擴展:

using System.ComponentModel; 
using System.Drawing; 

public static class MyExtensions 
{ 
    public static System.Drawing.Bitmap ToBitmap(this Pixbuf pix) 
    { 
     TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap)); 

     //// Possible file formats are: "jpeg", "png", "ico" and "bmp" 
     return (Bitmap)tc.ConvertFrom(pix.SaveToBuffer("jpeg")); 
    } 
} 

用法:

{ 
    Pixbuf pxb = new Pixbuf(pixSource); 
    Bitmap bmp = pxb.ToBitmap(); 
} 
+0

很不錯的!便利和簡單的一個包裝! – 2013-04-08 11:36:20

+0

它似乎沒有工作(指定png,jpeg或bmp)pixbuf與透明度...可能是Gdk.Pixbuf.SaveToBuffer()中的一個錯誤,或在位圖的緩衝區讀取(我正在使用單聲道)。將嘗試首先刪除透明度... – 2013-04-08 12:12:34

+0

今天早上嘗試了它。適用於純PNG和ICO,而不適用於BMP和JPEG。雖然JPEG根本不支持透明度,但BMP支持alpha通道。不知道爲什麼BMP不能在這裏工作。 – 2013-04-09 02:38:13

相關問題