Search code examples
phpimagepng

After Uploading PNG image without background gets black background in Laravel. Please check


 private function processImageUpload($image,$image_name){
        //using image png function to change any image from jpeg to png and store to public folder
        $img  = imagepng(imagecreatefromstring(file_get_contents($image)), config('app.LOGO_MEDIA_PATH').'/'.$image_name.'.png');

        /*
       * TODO : change the image replacing functionality
       * from static name to upload to uploads folder
       * and get URL form settings table
       */

        $url = "/front/common/img/".$image_name.'.png';
        return $url;
    }

I enable the imagick extension in php.ini file but didn't happen anything


Solution

  • I got the solution..Just need to add case with the image type. In this we can't convert png to png.

    private function processImageUpload($image,$image_name){
        if($image->getMimeType() !== "image/png"){
            //using image png function to change any image from jpeg to png and store to public folder
            $img  = imagepng(imagecreatefromstring(file_get_contents($image)), config('app.LOGO_MEDIA_PATH').'/'.$image_name.'.png');
        }else{
            $image->move(config('app.LOGO_MEDIA_PATH'), $image_name.'.png');
        }
    
        /*
        * TODO : change the image replacing functionality
        * from static name to upload to uploads folder
        * and get URL form settings table
        */
        
        $url = "/front/common/img/".$image_name.'.png';
        return $url;
    }