简体   繁体   English

从ImageMagick for PHP中的二进制字符串解码图像对象

[英]Decode image object from binary string in ImageMagick for PHP

I have a script that downloads favicons and turns them in to PNGs. 我有一个脚本,可下载收藏夹图标并将其转换为PNG。

To handle the conversion, I am using ImageMagick. 为了处理转换,我正在使用ImageMagick。 My current approach involves downloading the data, writing it to a file, converting the file, then deleting the originally downloaded file. 我当前的方法包括下载数据,将其写入文件,转换文件,然后删除最初下载的文件。 Here's what I mean: 这就是我的意思:

$source = 'http://google.com/favicon.ico';
$image = file_get_contents($source);

// I'd like to skip these lines
$favicon = fopen('favicon.ico', 'w');
fwrite($favicon, $image);
fclose($favicon);

$im = new Imagick();
$im->readimage('favicon.ico');
$im = $im->flattenImages();
$im->setImageFormat('png');
$im->writeImage('favicon.png');
unlink('favicon.ico');

This works, but ideally I could do it without writing the $image variable to the file favicon.ico and instead I might just convert the data within the $image variable and then $im->writeImage('favicon.png') on that. 这行得通,但是理想情况下,我可以在不将$image变量写入文件favicon.ico情况下做到这一点,而是可以只在$image变量中转换数据,然后在该变量上转换$im->writeImage('favicon.png')

I checked out the method getImageBlob but when I tried that I got this error: 我签出了方法getImageBlob但是当我尝试获取此错误时:

PHP Fatal error:  Uncaught exception 'ImagickException' with message 'no decode delegate for this image format `' @ error/blob.c/BlobToImage/364' in /home/vagrant/test/test_image.php:73
Stack trace:
#0 /home/vagrant/test/test_image.php(73): Imagick->readimageblob('\x00\x00\x01\x00\x02\x00\x10\x10\x00\x00\x01\x00 \x00h...')
#1 {main}
  thrown in /home/vagrant/test/test_image.php on line 73

Any ideas? 有任何想法吗?

You'll need to invoke Imagick::setFormat before reading blob. 在读取blob之前,您需要调用Imagick :: setFormat

<?php
$source = 'http://google.com/favicon.ico';
$image = file_get_contents($source);

$im = new Imagick();
$im->setFormat('ICO');
$im->readImageBlob($image);
$im = $im->flattenImages();
$im->setImageFormat('PNG');
$im->writeImage('favicon.png');

Update 更新资料

Flattening the .ico image may have negative effects on files containing more than one image. 展平.ico图像可能会对包含多个图像的文件产生负面影响。 Simplest solution would be to iterate over all the images, and determine which sub-image to use. 最简单的解决方案是遍历所有图像,并确定要使用哪个子图像。

$im = new Imagick();
$im->setFormat('ICO');
$im->readImageBlob($image);
for( $idx = 0, $len = $im->getNumberImages(); $idx < $len; $idx++ ) {
    // If this is the sub-image you want, do the following, else skip
    $im->setImageFormat('png');
    $im->setImageIndex($idx);
    $im->writeImage(sprintf('favicon_%d.png', $idx));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM