When I am using PHP Imagick() to resize and offer up an image for download, the resulting image is often truncated.
I can't diagnose when this happens, but it happens enough that it is a problem. In this code, $file is a much larger image file of which I want to order a smaller download.
if (file_exists($file)) {
$image = new Imagick();
$image->setResolution(150,150);
$image->readImage($file);
$image->resizeImage(1275,0,Imagick::FILTER_LANCZOS,1);
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=download.'.$extension);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
echo $image;
exit;
}
What's happening is, some of the time the files download correctly, and sometimes the image is truncated--only the top 30% of the image looks right and the rest is just blank. So the file dimensions are correct but the image data only makes it halfway.
What might be causing the problem--but still doesn't happen consistently--is that I am doing this with PDFs, JPEGs and PNGs alike, and outputting them as whatever their original extensions were.
Any suggestions?
EDIT: Figured it out, see below. Thanks!