Create a transparent png file using PHP

前端 未结 3 1187
我在风中等你
我在风中等你 2021-01-01 20:13

Currently I would like to create a transparent png with the lowest quality .

The code:



        
相关标签:
3条回答
  • 2021-01-01 20:50

    To 1) imagecreatefrompng('test.png') tries to open the file test.png which then can be edited with GD functions.

    To 2) To enable saving of the alpha channel imagesavealpha($img, true); is used. The following code creates a 200x200px sized transparent image by enabling alpha saving and filling it with transparency.

    <?php
    $img = imagecreatetruecolor(200, 200);
    imagesavealpha($img, true);
    $color = imagecolorallocatealpha($img, 0, 0, 0, 127);
    imagefill($img, 0, 0, $color);
    imagepng($img, 'test.png');
    
    0 讨论(0)
  • 2021-01-01 21:02

    1) You can create a new png file without any existing one. 2) You get a black color image because you use imagecreatetruecolor();. It creates a highest quality image with a black background. As you need a lowest quality image use imagecreate();

    <?php
    $tt_image = imagecreate( 100, 50 ); /* width, height */
    $background = imagecolorallocatealpha( $tt_image, 0, 0, 255, 127 ); /* In RGB colors- (Red, Green, Blue, Transparency ) */
    header( "Content-type: image/png" );
    imagepng( $tt_image );
    imagecolordeallocate( $background );
    imagedestroy( $tt_image );
    ?>
    

    You can read more in this article: How to Create an Image Using PHP

    0 讨论(0)
  • 2021-01-01 21:05

    Take a look at:

    • imagecolorallocatealpha
    • imagefill

    An example function copies transparent PNG files:

        <?php
        function copyTransparent($src, $output)
        {
            $dimensions = getimagesize($src);
            $x = $dimensions[0];
            $y = $dimensions[1];
            $im = imagecreatetruecolor($x,$y); 
            $src_ = imagecreatefrompng($src); 
            // Prepare alpha channel for transparent background
            $alpha_channel = imagecolorallocatealpha($im, 0, 0, 0, 127); 
            imagecolortransparent($im, $alpha_channel); 
            // Fill image
            imagefill($im, 0, 0, $alpha_channel); 
            // Copy from other
            imagecopy($im,$src_, 0, 0, 0, 0, $x, $y); 
            // Save transparency
            imagesavealpha($im,true); 
            // Save PNG
            imagepng($im,$output,9); 
            imagedestroy($im); 
        }
        $png = 'test.png';
    
        copyTransparent($png,"png.png");
        ?>
    
    0 讨论(0)
提交回复
热议问题