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

标签 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 );

最佳答案

你需要

imagesavealpha( $dest, true );

如果您打算重叠六边形的透明部分,

imagealphablending( $dest, true );

关于php - 使用 PHP GD 的透明六边形蒙版拼贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27722042/

相关文章:

php - 如果我们将查询存储到变量中,MySQL REPLACE 将不起作用

php - 在 drupal 模块中通过 Ajax 调用执行 PHP 代码

php - MySql PHPmyadmin 错误 #1062

php - 如果设置了数组,做点什么?

php - 安装了 GD 后 imageantialias 调用未定义函数错误

PHP - 将转换后的图像保存到文件夹中

php - laravel undefined variable : host

php - 防止 GD 图像库内存不足的故障安全方法? (PHP)

php - 创建图像而不将其存储为本地文件

php - 使用 GD 库进行蒙太奇或拼贴