Supporting HEIC images on websites

What are HEIC images

HEIC is Apple’s own version of the High-Efficiency Image File format (HEIF) which offers even more compression than the JPEG format without sacrificing quality meaning even smaller files. HEIC became the default photo file format on iOS 11 but at the time almost no website supported uploading these type of images. Things have improved slightly since then but there is still no support on most browsers meaning anyone wanting to support them needs to convert them to either JPEG or WEBP first.

Debian 10 (“Buster”) was the first Debian Linux distribution to offer some support but as you will see some solutions work better than others.

Using Imagick

sudo apt-get install php-imagick

Using the php-imagick library to process HEIC images in our tests only worked some of the time. A simple example shown below to convert an HEIC image to a JPEG generated errors for about half the HEIC images we tried

<?php
if (isset($_FILES['file']))
	{
	$size		= isset($_REQUEST["w"]) ? $_REQUEST["w"] :800 ;
	$source 	= $_FILES['file']['tmp_name'];	
	$output		= $_SERVER["DOCUMENT_ROOT"]."/tmp/".time().".jpg";
	
	$imagick 	= new Imagick($source);
	$imagick->resizeImage($size,0,Imagick::FILTER_LANCZOS,1);
	$imagick->setImageFormat('jpg');
	$imagick->setCompressionQuality(80);
	$imagick->writeImage($output);

	$image_data	= file_get_contents($output);
	$base64 = "data:image/jpeg;base64,".base64_encode($image_data);
	unlink($output);

	echo("<p><img src=\"$base64\" alt=\"\"/></p>");
	}
	?>
    
    <form id="myinventory" method="post" action="/heic2.php" enctype="multipart/form-data">
	<input id="photo" type="file" name="file" onchange="document.forms[0].submit()"/>
    </form>    

Several sites on Google suggested compiling Imagick with HEIC support but everything appeared set up correctly on the server so I’m not sure what the issue was:

Using LibHeif

The most reliable solution we found in testing was to use the libheif library instead.

apt-get install libheif1
<?php
if (isset($_FILES['file']))
	{
	$size		= isset($_REQUEST["w"]) ? $_REQUEST["w"] :800 ;
	$source 	= $_FILES['file']['tmp_name'];	
	$output		= $_SERVER["DOCUMENT_ROOT"]."/tmp/".time().".jpg";
		
	shell_exec(escapeshellcmd("/bin/heif-convert -q 80 ".$source." ".$output));
	
	$image_data = file_get_contents($output);
	$base64     = "data:image/jpeg;base64,".base64_encode($image_data);
	unlink($output);

	echo("<p><img src=\"$base64\" alt=\"\"/></p>");
	}
	?>
    
    <form id="myinventory" method="post" action="/heic2.php" enctype="multipart/form-data">
	<input id="photo" type="file" name="file" onchange="document.forms[0].submit()"/>
    </form>    

We'd love to hear from you!

If you think Bronco has the skills to take your business forward then what are you waiting for?

Get in Touch Today!

Discussion

Add a Comment

Get in touch