Re: GdkBitmap from black & white .png file



Le samedi 31 janvier 2009 Ã 20:11 +0000, Richard Shann a Ãcrit :
The Gdk functions to create bitmaps from data require xbm or xpm data. 
(For example gdk_bitmap_create_from_data ()). Why do I not see anything
to create a bitmap from a (b&w) .png image?

There are functions to convert a PNG with transparency (alpha component)
to a GdkBitmap according to a threshold. See
gdk_pixbuf_render_threshold_alpha()
http://library.gnome.org/devel/gdk/stable/gdk-Pixbufs.html#gdk-pixbuf-render-threshold-alpha

BTW, here is a function (not tested) adapted from some code I wrote,
which should create a GdkBitmap from a GdkPixbuf according to your black
and white PNG.
Feel free to test and fix it.

/*
 * Author: Yann Droneaud <ydroneaud mandriva com>
 *
 */
GdkBitmap *
my_gdk_bitmap_new_from_pixbuf_non_alpha(GdkDrawable *drawable, 
                                        GdkPixbuf *pixbuf)
{
 int width;
 int height;
 int rowstride;
 guchar *pixels;
 guint32 pixel;

 gchar *bitmap_data;
 int bitmap_rowstride;
 GdkBitmap *bitmap;

 g_assert(pixbuf != NULL);
 g_assert(gdk_pixbuf_get_colorspace(pixbuf) == GDK_COLORSPACE_RGB);
 g_assert(gdk_pixbuf_get_bits_per_sample(pixbuf) == 8);
 g_assert(gdk_pixbuf_get_has_alpha(pixbuf));
 g_assert(gdk_pixbuf_get_n_channels(pixbuf) == 4);

 width = gdk_pixbuf_get_width(pixbuf);
 height = gdk_pixbuf_get_height(pixbuf);
 rowstride = gdk_pixbuf_get_rowstride(pixbuf);
 pixels = gdk_pixbuf_get_pixels(pixbuf);

 /* round to byte boundary */
 bitmap_rowbytes = (width + 7) / 8;

 /* allocate a *cleared* buffer for the bitmap data */
 bitmap_data = (gchar *) g_malloc0(bitmap_rowbytes * height);
 g_assert(bitmap_data != NULL);

 for(y = 0; y < height; y++) {
   for(x = 0; x < width; x++) {

      /* WARNING: use 4 components, 8 bits per component */
      pixel = * (guint32 *) &pixels[(y * rowbytes) + (x * 4)];

      /* remove alpha component
       * WARNING: beware of endianess 
       */
      pixel &= (guint32) 0xffffff00UL; 

      /* if not black, it should be white */
      if (pixel != (guint32)0UL) {
        bitmap_data[(y * bitmap_rowbytes) + (x / 8)] |= 1 << (x % 8);
      }
   }
 }

 bitmap = gdk_bitmap_create_from_data(drawable, bitmap_data, width, height);

 g_free(bitmap_data);

 return bitmap;
}





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]