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

时间:2014-12-31 13:49:23

标签: php gd

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

$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 );

1 个答案:

答案 0 :(得分:2)

你需要

imagesavealpha( $dest, true );

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

imagealphablending( $dest, true );