Re: Adding alpha channel to existing GdkPixbuf

>  Am I out of my gourd?  The problem is that some of the PNG graphics I'm
>  loading into my GdkPixbuf's weren't created with alpha channels, while
>  some were.  I'd like for all of them to have alpha channels so I can
>  mask out their backgrounds.  Fortunately, the maskable backgrounds all
>  have a solid color, so I can at least detect it.

Here is an untested function to promote a pixbuf to have alpha.  If
people think this is generally useful, please tell me so that I can
document it and put it in gdk-pixbuf.

GdkPixbuf *
gdk_pixbuf_add_alpha (GdkPixbuf *pixbuf)
	ArtPixBuf *apb;
	ArtPixBuf *new_apb;
	GdkPixbuf *new_pixbuf;
	int x, y;

	g_return_val_if_fail (pixbuf != NULL, NULL);

	apb = pixbuf->art_pixbuf;
	g_return_val_if_fail (apb->format == ART_PIX_RGB, NULL);
	g_return_val_if_fail (apb->n_channels == 3 || apb->n_channels == 4, NULL);
	g_return_val_if_fail (apb->bits_per_sample == 8, NULL);

	if (apb->has_alpha) {
		new_apb = art_pixbuf_duplicate (apb);
		if (!new_apb)
			return NULL;

		return gdk_pixbuf_new_from_art_pixbuf (new_apb);

	new_pixbuf = gdk_pixbuf_new (ART_PIX_RGB, TRUE, 8, apb->width, apb->height);
	if (!new_pixbuf)
		return NULL;

	new_apb = new_pixbuf->art_pixbuf;

	for (y = 0; y < apb->height; y++) {
		guchar *src, *dest;

		src = apb->pixels + y * apb->rowstride;
		dest = new_apb->pixels + y * new_apb->rowstride;

		for (x = 0; x < apb->width; x++) {
			*dest++ = *src++;
			*dest++ = *src++;
			*dest++ = *src++;
			*dest++ = 255;

	return new_pixbuf;


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