替换PSD文件中的图像。

4

各位程序员朋友们!

我正在尝试构建一个工具,用于替换 .psd 文件中的图像。目前,我正在尝试使用 imagick/ImageMagic 扩展的 PHP 脚本进行探索。

如果有人能够帮助我使用 imagick 实现这个功能,或者指导我寻找其他解决方案,我将不胜感激。

问题是图像无法被替换。我已经尝试使用 setImageaddImage 两种方法。如果我在 if 语句中导出文件,它会显示新添加的图像,但是输出结果中并没有反映出这些变化。

以下是我尝试过的代码:

        $src = Storage::path('file.psd');
        $psd = new Imagick($src);

        foreach ($psd as $index => $layer) {

            // Skip the first layer
            if (! $index) {
                continue;
            }

            $imageProperties = $layer->getImageProperties();
            $label = $imageProperties['label'] ?? '';

            if (str($label)->lower()->startsWith(['#'])) {
                $layer->removeImage();
                $layer->setImage(new Imagick(Storage::path('image.png')));

            }
        }


        $psd->mergeImageLayers(Imagick::LAYERMETHOD_MERGE);
        $psd->setImageFormat('png');
        $psd->writeImage(Storage::path('output.png'));
        $psd->clear();
        $psd->destroy();

这是一个我尝试过的示例文件:https://mega.nz/file/H5FhQRRZ#Ta06TySXU5FIKAtx0DN87E3tjN2QSDoa3DAx0AQQbZ0

2
我的初始回答本来是“不支持PSD”,但经过快速搜索后,我被证明是错误的!好知道!我看到有人提到,第一层(可能是最底层)必须是一个扁平化的层,可能是一个背景层。也许可以试试这个? - Chris Haas
@ChrisHaas 我尝试过了,但是没能让它工作,今晚再试一次。 - platypusmaximus
@alxndr_k 看起来似乎没有任何方法可以真正替换数据。 - platypusmaximus
假设您可以获得Photoshop和扩展脚本工具包 (信息),也许结合使用脚本以及命令行方法运行工具包。 - Yarin_007
你说的“但是更改没有反映在输出中”是什么意思? - Yarin_007
显示剩余2条评论
2个回答

0

尝试使用 compositeImage() 图片

foreach ($psd as $index => $layer) {
    // Skip the first layer
    if (! $index) {
        continue;
    }

    $imageProperties = $layer->getImageProperties();
    $label = $imageProperties['label'] ?? '';

    if (str($label)->lower()->startsWith(['#'])) {
        $layer->compositeImage($newImage, Imagick::COMPOSITE_DEFAULT, 0, 0);
    }
}

尽管它没有解决我的问题,但它推动我找到了正确的方向。谢谢! - platypusmaximus

0
您可以使用PHP GD库来替换PSD文件中的图像。以下代码片段展示了如何实现此操作:
// Load the original PSD file into a GD resource
$psd = imagecreatefrompsd('original.psd');

// Load the new image into a GD resource
$newImage = imagecreatefromjpeg('new_image.jpg');

// Get the width and height of the new image 
$width = imagesx($newImage); 
$height = imagesy($newImage); 
 
// Copy the new image onto the original PSD resource 
imagecopyresampled($psd, $newImage, 0, 0, 0, 0, $width, $height, $width, $height); 
 
// Save the modified PSD file 
imagepsd($psd,'modified.psd');

据我所知,这不会替换图层中的图像,而是将图像覆盖在其上。如果应用于图像的任何其他滤镜作为“父图层”被PSD应用,则此方法将无效。 - platypusmaximus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接