問題描述
PHP Imagick:如何將自定義圖像屬性保存到文件 (PHP Imagick: How to save custom image property to file)
我有一個 PHP 應用程序,它正在使用 Image Magick (Imagick()
) 處理大量圖像,並且我正在嘗試將一段計算數據保存到圖像中以供讀取(如果可用)節省處理時間或使用 Imagick::setImageProperty()
和 Imagick::getImageProperty()
計算並保存以備下次使用。我在 CodeIgniter 2 中有一個測試控制器,如下所示:
class Example extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function property()
{
$im = new Imagick();
$im‑>newimage(50, 50, 'blue');
$im‑>setimageformat('jpg');
$im‑>setimageproperty('My‑App:My‑Prop', 'rawr');
var_dump($im‑>getimageproperty('My‑App:My‑Prop'));
$im‑>writeimage(getcwd().'/images/test/output.jpg');
echo '<br />'.var_dump($im‑>getimageproperty('My‑App:My‑Prop'));
echo '<img src="/images/test/output.jpg" /><br />';
$this‑>read();
}
public function read()
{
$im = new Imagick(getcwd().'/images/test/output.jpg');
var_dump($im‑>getimageproperty('My‑App:My‑Prop'));
}
}
前2次成功讀取該屬性,但是一旦根據保存的圖像實例化一個新的Imagick
對象,該屬性就無法讀取並返回false
:
string(4) "rawr" string(4) "rawr"
bool(false )
無法將自定義圖像屬性保存到文件中,還是我濫用了該類?
PS...我故意不使用 CodeIgniter 圖像庫,但是如果這對這種情況有幫助,我願意接受這個想法。
參考解法
方法 1:
This seems to be a limitation in the ImageMagick library and the JPEG image format. The short version is that only properties named 'comment' are persisted by the ImageMagick library for JPG images. See the code below for an example.
TBH I think the sensible thing to do would be to store your meta information separately from the image file. i.e. take the image file name, append ".json" and store the calculated data in there.
It will work, will avoid re‑saving the images if they haven't been modified and generally be a more robust solution than storing it in the image file.
$propertyNames = [
"comment",
"anything_else"
];
$formats = [
'jpg',
'png'
];
foreach ($formats as $format) {
foreach ($propertyNames as $propertyName) {
$imagick = new Imagick('./LittleRobin.jpg');
$imagick‑>setImageProperty($propertyName, "Modified value");
$imagick‑>setFormat($format);
$imagick‑>writeImage("./testModified.".$format);
$imagick2 = new Imagick("./testModified.".$format);
printf(
"After reloading '%s' property '%s' is:%s\n",
$format,
$propertyName,
var_export($imagick2‑>getImageProperty($propertyName), true)
);
}
}
Output is:
After reloading 'jpg' property 'comment' is:'Modified value'
After reloading 'jpg' property 'anything_else' is:false
After reloading 'png' property 'comment' is:'Modified value'
After reloading 'png' property 'anything_else' is:'Modified value'