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

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

    Taken the @dre010 idea, I have extended it to another function that works with any image type: PNG, JPG, JPEG or GIF and gives a unique name to the filename

    The function separate image data and image type

    function base64ToImage($imageData){
        $data = 'data:image/png;base64,AAAFBfj42Pj4';
        list($type, $imageData) = explode(';', $imageData);
        list(,$extension) = explode('/',$type);
        list(,$imageData)      = explode(',', $imageData);
        $fileName = uniqid().'.'.$extension;
        $imageData = base64_decode($imageData);
        file_put_contents($fileName, $imageData);
    }
    

提交回复
热议问题