Page 271 - Open Soource Technologies 304.indd
P. 271

Unit 11: Graphics



            11.4.2 Changing the Output Format                                                     Notes
            As you may have deduced, generating an image stream of a different type requires only two
            changes to the script: send a different Content-Type and use a different image-generating
            function. Example shows the JPEG version of the black square.
                          JPEG version of the black square.

            <?php
             $im = ImageCreate(200,200);
             $white = ImageColorAllocate($im,0xFF,0xFF,0xFF);

             $black = ImageColorAllocate($im,0x00,0x00,0x00);
             ImageFilledRectangle($im,50,50,150,150,$black);
             header(‘Content-Type: image/jpeg’);

             ImageJPEG($im);
            ?>
            11.4.3 Testing for Supported Image Formats

            If you are writing code that must be portable across systems that may support different image
            formats, use the  ImageTypes( ) function to check which image types are supported. This
            function returns a bitfield; you can use the bitwise AND operator (&) to check if a given bit
            is set. The constants IMG_GIF, IMG_JPG, IMG_PNG, and IMG_WBMP correspond to the
            bits for those image formats.

            Example generates PNG files if PNG is supported, JPEG files if PNG is not supported, and GIF
            files if neither PNG nor JPEG are supported.
                          Checking for image format support.

            <?php

            $im = ImageCreate(200,200);
            $white = ImageColorAllocate($im,0xFF,0xFF,0xFF);
            $black = ImageColorAllocate($im,0x00,0x00,0x00);
            ImageFilledRectangle($im,50,50,150,150,$black);
            if (ImageTypes(  ) & IMG_PNG) {
            header(“Content-Type: image/png”);
            ImagePNG($im);
            } elseif (ImageTypes(  ) & IMG_JPG) {

            header(“Content-Type: image/jpeg”);
            ImageJPEG($im);
            } elseif (ImageTypes(  ) & IMG_GIF) {
            header(“Content-Type: image/gif”);
            ImageGIF($im);
            }

            ?>


                                             LOVELY PROFESSIONAL UNIVERSITY                                   265
   266   267   268   269   270   271   272   273   274   275   276