4

PNG画像に透明な領域、ある種の「穴」を作成したい。したがって、この画像を背景画像の上に配置すると、その「穴」から背景の断片を見ることができます。フォーラムでこのコードを見つけました:

$imgPath = 'before.png';
$img = imagecreatefrompng($imgPath); // load the image
list($width,$height) = getimagesize($imgPath); // get its size
$c = imagecolortransparent($img,imagecolorallocate($img,255,1,254)); // create transparent color, (255,1,254) is a color that won't likely occur in your image
$border = 10;
imagefilledrectangle($img, $border, $border, $width-$border, $height-$border, $c); // draw transparent box
imagepng($img,'after.png'); // save

PNG画像に透明領域(この場合は長方形)を作成するために機能します。しかし、この png 画像を他の画像の上に配置すると、その領域の透明度が失われるため、結果の画像の中央に色付きの四角形ができてしまいます。誰か助けてくれませんか?

4

2 に答える 2

1

An alternative option would be using the PHP ImageMagick extension, Imagick.

You can create the rectangle by setting the background parameter of the Imagick::newImage function, the cicle using the ImagickDraw::circle function, and the key is to apply the circle using the Imagick::compositeImage and only copying the transparency over. This will prevent you from having a solid image with a transparent circle on top; everything that is transparent in the mask will be transparent on the original image.

The below code should do the trick (although I am sure it will need a few tweaks to meet your needs :P):

<?php

    $base = new Imagick("before.png");
    $base->cropImage(512, 512, 0, 0);
    $base->setImageMatte(true);

    $mask = new Imagick();
    $mask->newImage(512, 512, new ImagickPixel("transparent"));

    $circle = new ImagickDraw();
    $circle->setFillColor("black");
    $circle->circle(150, 150, 100, 100);

    $mask->drawImage($circle);

    $base->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);

    $base->writeImage('after.png');
    header("Content-Type: image/png");
    echo $base;

?>
于 2012-06-18T19:24:29.673 に答える
0

透明色にはこれを試してください:

$c = imagecolorallocatealpha($img,0,0,0,127);
于 2012-06-18T19:20:00.473 に答える