Joseph
Joseph

Reputation: 238

imagepng and imagegif

I need some help about PHP GD. Here is my piece of code.

    header("Content-type: image/gif");

    $image = imagecreatetruecolor(550, 20);
    imagealphablending($image, false);

    $col=imagecolorallocatealpha($image,255,255,255,127);
    $black = imagecolorallocate($image, 0, 0, 0);

    imagefilledrectangle($image,0,0,550,20,$col);
    imagealphablending($image, true);

    $font_path = 'font/arial.ttf';
    imagettftext($image, 9, 0, 16, 13, $black, $font_path, $lastlisten);
    imagesavealpha($image, true);

    imagepng($image);

The problem is when I use imagepng, it can show the png just fine like this. enter image description here

But if I use imagegif instead, it will become this. enter image description here

I did tried using different header for gif and png. The result for imagegif is still the same. The question is how do I make in order to display GIF version properly? Thanks you

Upvotes: 2

Views: 1855

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272066

GIF image supports a maximum of 256 colors. Most importantly, it only supports index transparency: a pixel can be 100% opaque or 100% transparent.

PNG on the other hand supports true (millions of) color images and supports alpha channel transparency. That means a pixel can be 100% opaque, 100% transparent or anything in between.

The PNG image you mentioned probably has its edges partially transparent therefore the browser can easily blend those pixels with the background color giving a smooth effect. PNG is a better choice.

Upvotes: 2

Alain
Alain

Reputation: 36954

First problem : your characters are ugly: that's because you need to set a palette with less colors when using imagecreatetruecolor.

$image = imagecreatetruecolor(550, 20);
imagetruecolortopalette($image, true, 256);

should solve this problem.

Second problem : there is no transparency.

As you can see on PHP manual,

imagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.

This function does not work with GIF files.

You can use imagecolortransparent instead but this will not be perfect because fonts has anti-aliasing to make their border sweeter.

Here is my code:

<?php

$lastlisten = "test test test test test test";

error_reporting(E_ALL);
header("Content-type: image/gif");

$image = imagecreatetruecolor(550, 20);
imagetruecolortopalette($image, true, 256);

$transparent=imagecolorallocatealpha($image,255,255,255,127);
imagecolortransparent( $image, $transparent);
imagefilledrectangle($image,0,0,550,20,$transparent);

$black = imagecolorallocate($image, 0, 0, 0);
$font_path = dirname(__FILE__) . '/font.ttf';
imagettftext($image, 9, 0, 16, 13, $black, $font_path, $lastlisten);

imagegif($image);

Result here

Hope this helps.

Upvotes: 1

Related Questions