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

后端 未结 15 2333
情话喂你
情话喂你 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);
    
    0 讨论(0)
  • 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; 
    }
    
    0 讨论(0)
  • 2020-11-22 03:27

    It worth to say that discussed topic is documented in RFC 2397 - The "data" URL scheme (https://tools.ietf.org/html/rfc2397)

    Because of this PHP has a native way to handle such data - "data: stream wrapper" (http://php.net/manual/en/wrappers.data.php)

    So you can easily manipulate your data with PHP streams:

    $data = 'data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
    
    $source = fopen($data, 'r');
    $destination = fopen('image.gif', 'w');
    
    stream_copy_to_stream($source, $destination);
    
    fclose($source);
    fclose($destination);
    
    0 讨论(0)
  • 2020-11-22 03:31

    It's simple :

    Let's imagine that you are trying to upload a file within js framework, ajax request or mobile application (Client side)

    1. Firstly you send a data attribute that contains a base64 encoded string.
    2. In the server side you have to decode it and save it in a local project folder.

    Here how to do it using PHP

    <?php 
    
    $base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.
    
    $filePath = "/MyProject/public/uploads/img/test.png";
    
    file_put_contents($filePath, base64_decode($base64String));
    
    ?>
    
    0 讨论(0)
  • 2020-11-22 03:34

    Try this:

    file_put_contents('img.png', base64_decode($base64string));
    

    file_put_contents docs

    0 讨论(0)
  • 2020-11-22 03:38

    One-linear solution.

    $base64string = 'data:image/png;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
    file_put_contents('img.png', base64_decode(explode(',',$base64string)[1]));
    
    0 讨论(0)
提交回复
热议问题