1

How do you convert a Gdk.Pixbuf (_pixbuf below) into a Windows Forms (System.Drawing) Bitmap? Below is code that uses Gtk.DotNet.Graphics, but it just gives a white image. Is there a better, more direct way, that works? I'm using C# on Mono, but I can convert if you have an answer in another language.

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);
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Doug Blank
  • 2,031
  • 18
  • 36

1 Answers1

2

You can use this extensions method:

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")); 
    }
}

Usage:

{
    Pixbuf pxb = new Pixbuf(pixSource);
    Bitmap bmp = pxb.ToBitmap();
}
Alina B.
  • 1,256
  • 8
  • 18
  • Very nice! Convenience and simplicity in one package! – Doug Blank Apr 08 '13 at 11:36
  • It doesn't seem to work (specifying png, jpeg, or bmp) with a pixbuf with transparency... may be a bug in Gdk.Pixbuf.SaveToBuffer(), or in the buffer reading of Bitmap (I'm using Mono). Will try removing transparency first... – Doug Blank Apr 08 '13 at 12:12
  • Tried it this morning. Worked for pure PNG and ICO, not for BMP and JPEG. While JPEG does not support transparency at all, BMP supports alpha channels. Not sure why BMP does not work here. – Alina B. Apr 09 '13 at 02:38