使用PHP imageCreateFromJpeg复制图像并保留其EXIF/IPTC数据?

tft*_*ftd 12 php gd iptc exif

我对存储有EXIF/IPTC数据的图像有一些问题.
当我使用imageCreateFromJpeg(旋转/裁剪等)时,新存储的文件不保留EXIF/IPTC数据.

我当前的代码如下所示:

<?php
// Before executing - EXIF/IPTC data is there (checked)
$image = "/path/to/my/image.jpg";
$source = imagecreatefromjpeg($image);
$rotate = imagerotate($source,90,0);
imageJPEG($rotate,$image);
// After executing  - EXIF/IPTC data doesn't exist anymore. 
?>
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?

dre*_*010 7

你没有做错任何事,但GD根本不涉及IPTC数据的Exif,因为它超出了GD的范围.

您将不得不使用第三方库或其他PHP扩展来从源图像中读取数据并将其重新插入到由其创建的输出图像中imagejpeg.

这里有一些感兴趣的库:pel(php exif库),php.net上的一个例子,展示如何使用pel做你想要的,php元数据工具包,iptcembed()函数.

  • 在创建图像之前或之后,您必须从源图像中提取元数据.由于您使用`imagejpeg`输出最终图像,因此必须在将其保存后将其写入最终图像. (2认同)
  • 为什么图书馆需要了解exif?为什么盲目地将特定的字节块复制到新图像是不够的?(我想EXIF只有一个块......) (2认同)
  • @Tomas 我虽然同样的事情。我惊讶地发现它没有复制它!而且因为不能通过 php 函数嵌入 EXIF,所以您需要自己编写一个类来将标题放入图像中 - 多么浪费时间! (2认同)

Thi*_*ala 7

以下是使用 gd 进行图像缩放以及使用 PEL 复制 Exif 和 ICC 颜色配置文件的示例:

function scaleImage($inputPath, $outputPath, $scale) {
    $inputImage = imagecreatefromjpeg($inputPath);
    list($width, $height) = getimagesize($inputPath);
    $outputImage = imagecreatetruecolor($width * $scale, $height * $scale);
    imagecopyresampled($outputImage, $inputImage, 0, 0, 0, 0, $width * $scale, $height * $scale, $width, $height);
    imagejpeg($outputImage, $outputPath, 100);
}

function copyMeta($inputPath, $outputPath) {
    $inputPel = new \lsolesen\pel\PelJpeg($inputPath);
    $outputPel = new \lsolesen\pel\PelJpeg($outputPath);
    if ($exif = $inputPel->getExif()) {
        $outputPel->setExif($exif);
    }
    if ($icc = $inputPel->getIcc()) {
        $outputPel->setIcc($icc);
    }
    $outputPel->saveFile($outputPath);
}

copy('https://i.stack.imgur.com/p42W6.jpg', 'input.jpg');
scaleImage('input.jpg', 'without_icc.jpg', 0.2);
scaleImage('input.jpg', 'with_icc.jpg', 0.2);
copyMeta('input.jpg', 'with_icc.jpg');
Run Code Online (Sandbox Code Playgroud)

输出图像:

无 ICC 输出 带有复制的 ICC 的输出

输入图像:

原图