Output raw image from Imagick image in PHP

21,492

Solution 1

You just need to echo your imagick object:

$img = new Imagick($file);
header('Content-Type: image/'.$img->getImageFormat());
echo $img;

Solution 2

If you're using HHVM it'll throw a fatal exception if you just try and echo the Imagick object so you'll need to call getimageblob();

$imagick = new Imagick('my-image.jpg');
header('Content-Type: image/' . $imagick->getImageFormat());
echo $imagick->getimageblob();

Solution 3

I believe what Schneck meant is:

header('Content-Type: '.$mime_type);
$fp = fopen('php://stdout', 'w+');
$image->writeImageFile($fp);
fclose($fp);

This may cause problems, especially in multipage files, so you should probably use:

ob_start();
$fp = fopen('php://output', 'w+');
$image->writeimagefile($fp); // or writeImagesFile for multipage PDF
fclose($fp);
$out = ob_get_clean();
header('Content-Length: '.strlen($out));
echo $out;

This is tested and working.

I realize this is an old question. The reason I'm posting this is that if you want to write a multipage PDF, this is the solution, as Nabab's solution only works for single images.

You can also use (PHP 5.1.0+):

$fp = fopen('php://temp', 'r+');
$image->writeimagesfile($fp);
rewind($fp);
$out = stream_get_contents($fp);
header('Content-Length: '.strlen($out));
fclose($fp);
echo $out;

This way seems to be faster if your PHP version supports it.

Before you downvote, the reason I added this as an answer and not a comment is I don't have sufficient reputation to comment. Hope that is alright. Just wanted to get this out there in case anyone needed it.

Share:
21,492

Related videos on Youtube

WASD42
Author by

WASD42

Web- and iPhone developer.

Updated on September 17, 2020

Comments

  • WASD42
    WASD42 over 3 years

    I'm using Imagick lib to do some modifications to original image. Then I'd like to output it directly to browser without saving. Is there a way to do that?

    I tried to use Imagick::writeImage('STDOUT') (empty output) and 'php://stdout' with error "Unable to write to file".

    Any ideas? :)

  • Álvaro González
    Álvaro González about 13 years
    As illustrated in example #1: es2.php.net/manual/en/imagick.examples-1.php
  • gnud
    gnud about 13 years
    I'd go with header('Content-Type: image/'.$img->getImageFormat()); -- but otherwise very nice :)
  • Tymur Valiiev
    Tymur Valiiev about 4 years
    If, for some reason, you do not want to echo image, you can get its content by calling $img->__toString()