Search code examples
imagemagickimagickparse-errorphp-7.2

Imagick causing output parseerror


I'm using php 7.2 and ImageMagick-7.0.8-12. I'm using it to create thumbnails like so:

function thumbimg($sourcePath, $thumbPath) {
    try {
        if (file_exists($sourcePath)) {
            $imagick = new Imagick();
            $imagick->readImage($sourcePath);
            $imagick->setImageFormat("jpg");
            header('Content-Type: image/jpeg');
            $imagick->writeImage($thumbPath);
            $imagick->clear();
            $imagick->destroy();
            chmod($thumbPath, 0755);
            return;
        }
    } catch (ImagickException $e) {
        echo $this->raiseError('Could not save image to file: ' . $e->getMessage(), IMAGE_TRANSFORM_ERROR_IO);
    }
    return;
}

The php script does return an echo'ed JSON as designed, but when I look at the network return preview it shows a blank image with the post link to that script. This behavior starts on the line $imagick = new Imagick(); Prior to that it behaves normally. While I do get the desired JSON, it messes with other functions that produce outputs.


Solution

  • I would look for another Imagick example as yours looks a bit of a mess. You have a header in the middle of your code and that is used for the display. No idea why you have a chmod and I would have thought if it was required it would be at the start on the Imagick code. I also do not see any thumbnailing code.

    Try this:

    $im = new Imagick($input);
    $im->resizeImage( 100, 100, imagick::FILTER_LANCZOS, TRUE );
    $im->writeImage('resizeImage.jpg'); 
    $im->destroy();
    

    ( The filter is optional as Imagick will pick the best filter to use when increasing or decreasing size. )

    I think as @Mark Setchell says the destroy is unnecessary