Error in Writing to Image file from PHP

前端 未结 4 1231
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 06:23

I am attempting to write to an image file from a blob.

 if($_POST[\'logoFilename\'] != \'undefined\'){
  $logoFile = fopen($_POST[\'logoFilename\'], \'w\') o         


        
4条回答
  •  不知归路
    2021-01-19 07:03

    This function will save data uri to file:

    function saveDataUri($blob, $filename = null) 
    {
    
        // generate unique name basing on content
        if (empty($filename)) {
            $filename = md5($blob);
        }
    
        // parse data URI
        $semiPos = strpos($blob, ';', 5);
        $comaPos = strpos($blob, ',', 5);
        $mime = substr($blob, 5, $semiPos - 5);
        $data = substr($blob, $comaPos + 1);
    
        $isEncoded = strpos(substr($blob, $semiPos, $comaPos), 'base64');
    
        if ($isEncoded) {
            $data = base64_decode($data);
        }
    
    
        // save image data to file
        switch ($mime) {
               case 'image/png':
                    $ext = 'png';
                break;
               case 'image/gif':
                    $ext = 'gif';
                    break;
               case 'image/jpg':
               case 'image/jpeg':
               default:
                    $ext = 'jpg';
                    break;  
        }
    
        $outFile = $filename . '.' . $ext;
        $funcName = 'image' . $ext;
        $result = $funcName(imagecreatefromstring($data), $outFile);
    
        if ($result) {
    
            return $outFile;
        }
    
        return $result;
    }
    

    Usage in your case:

    // some_validation($_POST);
    $filename = saveDataUri($_POST['logoImage']);
    echo '' . $filename . '';
    

提交回复
热议问题