Search code examples
phpimagick

Imagick - Can't read image files from URL.


I'm using this snippet for reading images on different websites:

$image = new Imagick('http://lp.hm.com/hmprod?set=key[source],value[/model/2012/P01 05156 06204 80 1175 4.jpg]&set=key[rotate],value[]&set=key[width],value[]&set=key[height],value[]&set=key[x],value[]&set=key[y],value[]&set=key[type],value[STILL_LIFE_FRONT]&call=url[file:/product/large]');

But sometimes, I get an error like this (about 20% of the time):

ImagickException

Unable to read the file: http://lp.hm.com/hmprod?set=key[source],value[/model/2012/P01 05156 06204 80 1175 4.jpg]&set=key[rotate],value[]&set=key[width],value[]&set=key[height],value[]&set=key[x],value[]&set=key[y],value[]&set=key[type],value[STILL_LIFE_FRONT]&call=url[file:/product/large]

Imagick->__construct()

The error seems to be consistent through this whole domain, but sometimes it's different from image to image on the same domain.

Questions

Why is this a problem?
How can we fix it?
Is there an alternative solution?


Solution

  • STEP 1 : GET URL

    $url = 'http://blablabla.com/blabla.jpeg';
    

    STEP 2 : Save blog content to a variable

    $image = file_get_contents($url);
    

    STEP 3 : Create Imagick object

    $img = new Imagick();
    

    STEP 4 : Instruct imagick object to read blob content of the image

    $img -> readImageBlob($image);
    

    STEP 5 : Save (or do operations) on image

    $img -> writeImage('/var/www/html/uploads/img.jpg');
    

    STEP 6 : Destroy imagick instance

    $img -> destroy();