Copy an image and preserve its EXIF/IPTC data with PHP imageCreateFromJpeg?

三世轮回 提交于 2021-02-16 05:55:07

问题


I having some problems with an image that has EXIF/IPTC data stored in it.
When I use imageCreateFromJpeg (to rotate/crop or etc) the newly stored file doesn't preserve the EXIF/IPTC data.

My current code looks like this:

<?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. 
?>

Am I doing something wrong?


回答1:


You aren't doing anything wrong, but GD doesn't deal with Exif of IPTC data at all as its beyond the scope of what GD does.

You will have to use a 3rd party library or other PHP extension to read the data from the source image and re-insert it to the output image created by imagejpeg.

Here are some libraries of interest: pel (php exif library), an example on php.net showing how to use pel to do what you want, php metadata toolkit, iptcembed() function.




回答2:


Here is an example of image scaling using gd, and copying Exif and ICC color profile using PEL:

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

Output images:

Input image:



来源:https://stackoverflow.com/questions/10182890/copy-an-image-and-preserve-its-exif-iptc-data-with-php-imagecreatefromjpeg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!