Convert .HEIC to .JPG with ImageMagick in PHP
Your current approach attempts to leverage ImageMagick's native capabilities through PHP's Imagick extension, but there is a fundamental misunderstanding of how the library handles file paths versus memory streams. The command mogrify -format jpg *.HEIC works on the filesystem because mogrify expects existing files at specific locations and writes output to new files or overwrites originals depending on flags. When you try to simulate this behavior using PHP's readImageFile() with a resource handle, you are loading the image into memory, but the subsequent call to setFileName() does not magically convert that in-memory object into a file stream ready for download without explicitly writing it to disk first.
The specific error you are encounteringâ"It looks like we don't support this file format"âon Windows is almost certainly unrelated to the HEIC conversion itself. Instead, it indicates that the resulting file data being served by PHP is corrupted or incomplete. This usually happens because readfile() attempts to read from an object handle ($image_to_convert) rather than a string or a valid file path. The Imagick class manages internal buffers for reading and writing, but it does not expose itself as a readable stream in the way fopen expects unless you explicitly write the content to a temporary file.
To solve this, you must bridge the gap between the in-memory Imagick object and the physical filesystem. The standard pattern involves creating a unique temporary file path for the output, writing the converted image there using Imagick's writeImage() method, and then streaming that file to the browser. This ensures that any internal buffer flushing or format-specific header writing performed by ImageMagick completes successfully before the data is sent over HTTP.
Here is a robust implementation that adheres to this workflow:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_FILES['image_url']['name'])) {
echo "No File uploaded";
exit;
}
// Define the directory where temporary files are stored
$uploadDir = sys_get_temp_dir();
// Generate a unique filename to avoid collisions in multi-user environments
$extension = pathinfo($_FILES['image_url']['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '.jpg';
$filepath = $uploadDir . '/' . $filename;
try {
// Load the image from the temporary upload location
$uploadedImage = fopen($_FILES['image_url']['tmp_name'], 'rb');
$image_to_convert = new Imagick();
$image_to_convert->readImageFile($uploadedImage);
// Close the file handle; Imagick has finished reading
fclose($uploadedImage);
// Set the output format
$image_to_convert->setFormat('jpg');
// Write the converted image to a temporary file on disk
$image_to_convert->writeImage($filepath);
// Stream the file content directly to the browser
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Description: File Transfer');
// Read the specific file path, not the Imagick object handle
readfile($filepath);
} catch (Exception $e) {
echo "Conversion failed: " . $e->getMessage();
}
}
One critical detail often overlooked is the security implication of saving files to sys_get_temp_dir(). Since this directory is shared across processes on a Unix server, you must ensure that the generated filename contains no path traversal characters and ideally has a randomized name, which uniqid() provides. Additionally, always close file handles immediately after passing them to Imagick methods like readImageFile() or writeImage(). Holding onto open file descriptors can lead to resource exhaustion if your application processes high volumes of uploads.
If you are building this as part of a larger Laravel ecosystem, remember that while the native imagick package works well for standalone scripts, integrating it into a web server context requires careful attention to permissions. The PHP process running on your Unix server must have write access to the temporary directory and read access to the uploaded file's temporary location. Without these specific filesystem permissions, the conversion will fail silently or throw permission errors that are difficult to debug without checking error_log.
For production environments where you cannot rely on sys_get_temp_dir() being writable or secure enough, consider configuring a dedicated temporary directory within your application's storage structure (e.g., storage/app/temp/) and ensuring the web server user owns it. This approach isolates converted files from system-wide transient data and makes cleanup easier via standard cron jobs that wipe out directories older than a certain age.
Ultimately, the key to success is respecting the lifecycle of the ImageMagick object: read from memory, write to disk, then stream from disk. Attempting to skip the disk write step when working with complex formats like HEIC often results in malformed output files that fail validation on client devices.