与PIL相对应图像.粘贴在PHP中

2024-04-20 03:01:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我被要求将一个Python应用程序移植到PHP(我不太喜欢PHP)。在

我在移植时遇到困难的部分使用了一组单色的“模板”图像,这些图像基于奇妙的Map Icons Collectionby Nicolas Mollet。这些模板图像用于创建具有自定义背景和前景颜色的图标。皮尔斯图像.粘贴用于使用模板图像作为alpha遮罩以选定颜色“粘贴”图标前景。例如:

icon creation

我如何在PHP中复制这个呢?除了逐像素地做这件事之外,还有其他选择吗?在

[更新]

我不为我的PHP技能感到骄傲。。。到目前为止我所掌握的:

<?php

header('Content-type: image/png');

// read parameters: icon file, foreground and background colors
$bgc = sscanf(empty($_GET['bg']) ? 'FFFFFF' : $_GET['bg'], '%2x%2x%2x');
$fgc = sscanf(empty($_GET['fg']) ? '000000' : $_GET['fg'], '%2x%2x%2x');
$icon = empty($_GET['icon']) ? 'base.png' : $_GET['icon'];

// read image information from template files
$shadow = imagecreatefrompng("../static/img/marker/shadow.png");
$bg = imagecreatefrompng("../static/img/marker/bg.png");
$fg = imagecreatefrompng("../static/img/marker/" . $icon);
$base = imagecreatefrompng("../static/img/marker/base.png");
imagesavealpha($base, true); // for the "shadow"

// loop over every pixel
for($x=0; $x<imagesx($base); $x++) {
    for($y=0; $y<imagesy($base); $y++) {
        $color = imagecolorsforindex($bg, imagecolorat($bg, $x, $y));
        // templates are grayscale, any channel serves as alpha
        $alpha = ($color['red'] >> 1) ^ 127; // 127=transparent, 0=opaque.
        if($alpha != 127) { // if not 100% transparent
            imagesetpixel($base, $x, $y, imagecolorallocatealpha($base, $bgc[0], $bgc[1], $bgc[2], $alpha));
        }
        // repeat for foreground and shadow with foreground color
        foreach(array($shadow, $fg) as $im) {
            $color = imagecolorsforindex($im, imagecolorat($im, $x, $y));
            $alpha = ($color['red'] >> 1) ^ 127;
            if($alpha != 127) {
                imagesetpixel($base, $x, $y, imagecolorallocatealpha($base, $fgc[0], $fgc[1], $fgc[2], $alpha));
            }
        }       
    }
}
// spit image
imagepng($base);
// destroy resources
foreach(array($shadow, $fg, $base, $bg) as $im) {
    imagedestroy($im);
}

?>

工作正常,性能也不错。在


Tags: 图像alphabasegetpngcoloriconbg
1条回答
网友
1楼 · 发布于 2024-04-20 03:01:46

根据我的评论,ImageMagick可以做到这一点。但是,您已经指出,这对于您的用例可能不是最佳的,所以考虑使用GD2。在PHP站点上有一个演示如何做image merging。在

我想这可以在任何(相当新的)默认PHP安装上完成。在

相关问题 更多 >