How to save a PNG image server-side, from a base64 data string

后端 未结 15 2359
情话喂你
情话喂你 2020-11-22 03:18

I\'m using Nihilogic\'s \"Canvas2Image\" JavaScript tool to convert canvas drawings to PNG images. What I need now is to turn those base64 strings that this tool generates,

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 03:41

    This function should work. this has the photo parameter that holds the base64 string and also path to an existing image directory should you already have an existing image you want to unlink while you save the new one.

     public function convertBase64ToImage($photo = null, $path = null) {
        if (!empty($photo)) {
            $photo = str_replace('data:image/png;base64,', '', $photo);
            $photo = str_replace(' ', '+', $photo);
            $photo = str_replace('data:image/jpeg;base64,', '', $photo);
            $photo = str_replace('data:image/gif;base64,', '', $photo);
            $entry = base64_decode($photo);
            $image = imagecreatefromstring($entry);
    
            $fileName = time() . ".jpeg";
            $directory = "uploads/customer/" . $fileName;
    
            header('Content-type:image/jpeg');
    
            if (!empty($path)) {
                if (file_exists($path)) {
                    unlink($path);
                }
            }
    
            $saveImage = imagejpeg($image, $directory);
    
            imagedestroy($image);
    
            if ($saveImage) {
                return $fileName;
            } else {
                return false; // image not saved
            }
        }
    }
    

提交回复
热议问题