18

現在、最低品質の透過pngを作成したいと考えています。

コード:

<?php
function createImg ($src, $dst, $width, $height, $quality) {
    $newImage = imagecreatetruecolor($width,$height);
    $source = imagecreatefrompng($src); //imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.
    imagecopyresampled($newImage,$source,0,0,0,0,$width,$height,$width,$height);
    imagepng($newImage,$dst,$quality);      //imagepng() creates a PNG file from the given image. 
    return $dst;
}

createImg ('test.png','test.png','1920','1080','1');
?>

ただし、いくつかの問題があります。

  1. 新しいファイルを作成する前に、png ファイルを指定する必要がありますか? または、既存のpngファイルなしで作成できますか?

    警告: imagecreatefrompng(test.png): ストリームを開けませんでした: そのようなファイルまたはディレクトリはありません

    C:\DSPadmin\DEV\ajax_optipng1.5\create.php 4行目

  2. エラーメッセージがありますが、それでもpngファイルが生成されますが、ファイルが黒色の画像であることがわかりました。透明にするためにパラメータを指定する必要がありますか?

ありがとう。

4

3 に答える 3

51

1) GD 機能で編集できるimagecreatefrompng('test.png')ファイルを開こうとします。test.png

2) アルファ チャネルの保存を有効にするには、imagesavealpha($img, true);使用します。次のコードは、アルファ保存を有効にして透明度で塗りつぶすことにより、サイズが 200x200px の透明な画像を作成します。

<?php
$img = imagecreatetruecolor(200, 200);
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagepng($img, 'test.png');
于 2013-06-24T09:18:11.333 に答える
7

を見てみましょう:

関数の例では、透明な PNG ファイルをコピーします。

    <?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");
    ?>
于 2013-06-24T09:22:00.853 に答える
2

1) 既存の png ファイルがなくても、新しい png ファイルを作成できます。2) を使用しているため、黒色の画像が得られますimagecreatetruecolor();。黒の背景で最高品質の画像を作成します。最低品質の画像を使用する必要があるため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 );
?>

詳細については、次の記事を参照してください: PHP を使用してイメージを作成する方法

于 2013-11-30T08:44:22.387 に答える