Open TGA with PHP: imagecreatefromtga

Need to read TGA files in PHP? Here’s an implementation of imagecreatefromtga, which reads 24 bit TGA images both RLE compressed and uncompressed as these are the most popular variants of TGA files. If you need support for any other variant of TGA (like RLE compressed 32 bpp image)- leave a comment and perhaps one day I will find a minute to implement support of it.

You can use it as any other imagecreatefrom* function:

include 'tga.php';
//convert TGA to PNG
$im = imagecreatefromtga('test.tga');
imagepng($im, 'test.png');

You can also read small fraction of TGA file to get its width, height, number of bits per pixel and also check if this is a proper TGA file (inproper TGA will return zeroes):

list($width, $height, $type, $bits, $tga_type) = getimagesizetga('test1.tga');
echo 'Width: ' . $width . ' Height: '. $height;

Update: 24.08.2010
Gašper Kozak spotted a bug (thanks!) in the class, so I fixed it and uploaded a new version. This bug was showing some Notices, so it was not that bad :)

This entry was posted on Tuesday, February 9th, 2010 at 9:14 pm and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

5 Responses to “Open TGA with PHP: imagecreatefromtga”

  1. Dmitry Says:

    Thank you for this helpful script.

    But could you create support for 32px TGA images?

    Best regards.

    Dmitry.

  2. admin Says:

    I think I will add support for 32bit images, but I don’t have enough time right now to do this, so it will need to wait.

  3. Quim Says:

    32bit images support:

    line 99:
    if ($header['pixel_size'] != 24 && $header['pixel_size'] != 24)

    line 153:
    $num_bytes = $header['pixel_size']/8;
    $pixels = str_split($data, $num_bytes);

  4. admin Says:

    Thanks, Quim!

  5. ZeroSama Says:

    I think you ment

    line 99:
    if ($header['pixel_size'] != 24 && $header['pixel_size'] != 32)

Leave a Reply

 
TopOfBlogs Web Development & Design Blogs