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

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

    You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

    $data = 'data:image/png;base64,AAAFBfj42Pj4';
    
    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);
    
    file_put_contents('/tmp/image.png', $data);
    

    And as a one-liner:

    $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
    

    An efficient method for extracting, decoding, and checking for errors is:

    if (preg_match('/^data:image\/(\w+);base64,/', $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 = str_replace( ' ', '+', $data );
        $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');
    }
    
    file_put_contents("img.{$type}", $data);
    

提交回复
热议问题