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

后端 未结 15 2324
情话喂你
情话喂你 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:26

    based on drew010 example I made a working example for easy understanding.

    imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data 
    
    function imagesaver($image_data){
    
        list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating 
    
        if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
            $data = substr($data, strpos($data, ',') + 1);
            $type = strtolower($type[1]); // jpg, png, gif
    
            if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
                throw new \Exception('invalid image type');
            }
    
            $data = base64_decode($data);
    
            if ($data === false) {
                throw new \Exception('base64_decode failed');
            }
        } else {
            throw new \Exception('did not match data URI with image data');
        }
    
        $fullname = time().$type;
    
        if(file_put_contents($fullname, $data)){
            $result = $fullname;
        }else{
            $result =  "error";
        }
        /* it will return image name if image is saved successfully 
        or it will return error on failing to save image. */
        return $result; 
    }
    

提交回复
热议问题