使用 PHP GD 的透明六边形蒙版拼贴


Transparent hexagon-masked collage using PHP GD

我正在使用GD创建一行六边形蒙版图像,但我无法弄清楚如何在每个蒙版周围创建透明度。拼贴本身工作得很好,但它为图像添加了白色、不透明的背景,尽管在imagecolorallocatealpha函数中的 alpha 参数上设置了 127。该代码基于此 SO 答案。

$count = 0;
// Full size image
$dest = imagecreatetruecolor( 195 * count( $images ), 230 );
// Loop image array
foreach ( $images as $image_array ) {
    // Get image source and create raw format
    $image_src = wp_get_attachment_image_src( $image_array['image'], 'hexagon' );
    $raw = strpos( 'png', $image_src[0] !== false ) ? imagecreatefrompng( $image_src[0] ) : imagecreatefromjpeg( $image_src[0] );
    $w = imagesx( $raw );
    $h = imagesy( $raw );
    /* Shape(ish)
     /'
    |  |
     '/
    */
    $points = array(
        0.5 * $w, 0,
        0, 0.23 * $h,
        0, 0.72 * $h,
        0.5 * $w, $h,
        $w, 0.72  * $h,
        $w, 0.23  * $h
    );
    // Create the mask
    $mask = imagecreatetruecolor( $w, $h );
    imagefilledpolygon( $mask, $points, 6, imagecolorallocate( $mask, 255, 0, 0 ) );
    // New image
    $image = imagecreatetruecolor( $w, $h );
    imagealphablending( $image, false );
    imagesavealpha( $image, true );
    // Transparency
    $transparent = imagecolorallocatealpha( $raw, 255, 255, 255, 127 );
    imagefill( $image, 0, 0, $transparent );
    // Pixel mapping
    for( $x = 0; $x < $w; $x++ ) {
        for ( $y=0; $y < $h; $y++ ) { 
            $m = imagecolorsforindex( $mask, imagecolorat( $mask, $x, $y ) );
            if( $m['red'] ) {
                $color = imagecolorsforindex( $raw, imagecolorat( $raw, $x, $y ) );
                imagesetpixel( $image, $x, $y, imagecolorallocatealpha( $image,
                                  $color['red'],
                                  $color['green'], 
                                  $color['blue'],
                                  $color['alpha']
                                )
                            );
            }
        }
    }
    // Merge to the original image
    imagecopymerge( $dest, $image, ( 195 * $count ), 0, 0, 0, imagesx( $image ), imagesy( $image ), 100 );
    $count++;
}
$path = get_template_directory() . '/assets/images/tile_image_one.png';
imagepng( $dest, $path, 0, NULL );
imagedestroy( $dest );

你需要

imagesavealpha( $dest, true );

如果你打算重叠六边形的透明位,

imagealphablending( $dest, true );