convert .heic image to jpg image format in laravel
Asked Answered
E

3

6

I have added intervention/image package to convert image format in laravel.

image converted successfully but after uploading image quality was so bad.

Original Image Original Image

Uploaded Image Uploaded Image

image blur

$img =(string) Image::make($image['base64'])
    ->resize(500, 500)->encode('jpg',100);;
$img = base64_encode($img);
Engelhart answered 7/4, 2020 at 13:11 Comment(0)
C
6

To convert Heic image you have to use imagick, can you use this instead

This is how to install https://ourcodeworld.com/articles/read/645/how-to-install-imagick-for-php-7-in-ubuntu-16-04

try {
    $image = new \Imagick();
    $image->readImageBlob($image['base64']));
    $image->setImageFormat("jpeg");
    $image->setImageCompressionQuality(100);
    $image->writeImage($targetdir.$uid.".jpg"); 
} 
catch (\ImagickException $ex) {
    /**@var \Exception $ex */
    return new JSONResponse(["error" => "Imagick failed to convert the images, check if you fulfill all requirements." , "details" => $ex->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR);
}
Comprehensible answered 10/4, 2020 at 12:35 Comment(2)
Sorry but this doesn't work. I still get an error: Unable to read image from path (/tmp/phpoMTE96).Rapp
Imagick verion 3.x.x doesnt support HEIC format.Disgusting
T
1

A bit late, but I had the same problem. I managed to do it with the heic2any js library (https://github.com/alexcorvi/heic2any/blob/master/docs/getting-started.md)

I converted the picture on client side, then gave it to the input in client side. Server is seeing it as it was originally uploaded as jpg.

    function convertHeicToJpg(input)
    {
        var fileName = $(input).val();
        var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
        if(fileNameExt == "heic") {
            var blob = $(input)[0].files[0]; //ev.target.files[0];
            heic2any({
                blob: blob,
                toType: "image/jpg",
            })
                .then(function (resultBlob) {

                    var url = URL.createObjectURL(resultBlob);
                    $(input).parent().find(".upload-file").css("background-image", "url("+url+")"); //previewing the uploaded picture
                    //adding converted picture to the original <input type="file">
                    let fileInputElement = $(input)[0];
                    let container = new DataTransfer();
                    let file = new File([resultBlob], "heic"+".jpg",{type:"image/jpeg", lastModified:new Date().getTime()});
                    container.items.add(file);

                    fileInputElement.files = container.files;
                    console.log("added");
                })
                .catch(function (x) {
                    console.log(x.code);
                    console.log(x.message);
                });
        }
    }

    $("#input").change(function() {
            convertHeicToJpg(this);

     });

What I am doing is converting the heic picture to jpg, then previewing it. After that I add it to the original input. Server side will consider it as an uploaded jpg. Some delay can appear while converting, therefore I placed a loader gif while uploading.

Tridentine answered 12/4, 2021 at 16:6 Comment(0)
I
0

The heic2any js library helped me accomplish this (https://github.com/alexcorvi/heic2any/blob/master/docs/getting-started.md)

On the client side, I converted the picture, then gave it to the server input. The server sees it as it was originally uploaded as PNG.

    $('#files').on('change' , function(){
          var total_file=document.getElementById("files").files.length;
 
        for(var i=0;i<total_file;i++)
        {
          files = event.target.files[i];
          var fileName = files.name;
          var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
          objURL = URL.createObjectURL(event.target.files[i]);
          if(fileNameExt == "heic") {
            objURL = await convertHeicToJpg(input , i);
       
         }
        })
        
        async function convertHeicToJpg(input , i)
                {
                        var blobfile = $(input)[0].files[i]; //ev.target.files[0];
            
                        let blobURL = URL.createObjectURL(blobfile);
                    
                        // convert "fetch" the new blob url
                        let blobRes = await fetch(blobURL)
            
                        // convert response to blob
                        let blob = await blobRes.blob()
            
                        // convert to PNG - response is blob
                        let resultBlob = await heic2any({ blob })
            
                        console.log(resultBlob)
                        var url = URL.createObjectURL(resultBlob);
                               
                        let fileInputElement = $(input)[0];
                        let container = new DataTransfer();
                        let file = new File([resultBlob], "heic"+".png",{type:"image/png", lastModified:new Date().getTime()});
                        container.items.add(file);
            
                        fileInputElement.files[0] = container.files;
                        uploadFile(container.files);
                        console.log("added");
                        console.log(url);
                        
                        return url ;
               
                }
            
            function uploadFile(files)
            {
              
              console.log(files);
              var error = '';
              var form_data = new FormData();
              for(var count = 0; count<files.length; count++)
              {
               var name = files[count].name;
               var extension = name.split('.').pop().toLowerCase();
               form_data.append("files[]", files[count]);
              }
               $.ajax({
                url:"<?php echo base_url(); ?>Property/upload", 
                method:"POST",
                data:form_data,
                contentType:false,
                cache:false,
                processData:false,
                dataType:'JSON',
                beforeSend:function(){
                    //..processing  
                },
                success:function(data)
                {
                  
                  alert('image uploade')
                }
               })
             
            }    
Isaiah answered 18/11, 2021 at 10:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.