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

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

    If you want to randomly rename images, and store both the image path on database as blob and the image itself on folders this solution will help you. Your website users can store as many images as they want while the images will be randomly renamed for security purposes.

    Php code

    Generate random varchars to use as image name.

    function genhash($strlen) {
            $h_len = $len;
            $cstrong = TRUE;
            $sslkey = openssl_random_pseudo_bytes($h_len, $cstrong);
            return bin2hex($sslkey);
    }
    $randName = genhash(3); 
    #You can increase or decrease length of the image name (1, 2, 3 or more).
    
    

    Get image data extension and base_64 part (part after data:image/png;base64,) from image .

    $pos  = strpos($base64_img, ';');
    $imgExten = explode('/', substr($base64_img, 0, $pos))[1];
    $extens = ['jpg', 'jpe', 'jpeg', 'jfif', 'png', 'bmp', 'dib', 'gif' ];
    
    if(in_array($imgExten, $extens)) {
    
       $imgNewName = $randName. '.' . $imgExten;
       $filepath = "resources/images/govdoc/".$imgNewName;
       $fileP = fopen($filepath, 'wb');
       $imgCont = explode(',', $base64_img);
       fwrite($fileP, base64_decode($imgCont[1]));
       fclose($fileP);
    
    }
    
    # => $filepath <= This path will be stored as blob type in database.
    # base64_decoded images will be written in folder too.
    
    # Please don't forget to up vote if you like my solution. :)
    
    0 讨论(0)
  • 2020-11-22 03:47

    try this...

    $file = $_POST['file']; //your data in base64 'data:image/png....';
    $img = str_replace('data:image/png;base64,', '', $file);
    file_put_contents('img/imag.png', base64_decode($img));
    
    0 讨论(0)
  • 2020-11-22 03:48

    I had to replace spaces with plus symbols str_replace(' ', '+', $img); to get this working.

    Here is the full code

    $img = $_POST['img']; // Your data 'data:image/png;base64,AAAFBfj42Pj4';
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    file_put_contents('/tmp/image.png', $data);
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题