从PHP写入映像文件时出错


Error in Writing to Image file from PHP

我正在尝试从blob写入图像文件。

 if($_POST['logoFilename'] != 'undefined'){
  $logoFile = fopen($_POST['logoFilename'], 'w') or die ("Cannot create ".$_POST['logoFilename']);
  fwrite($logoFile, $_POST['logoImage']);
  fclose($logoFile);
}

在前面的代码片段中,$_POST['logoImage']是一个BLOB。文件被正确地写入根目录,但是无法打开文件。在ubuntu 11.04中,我收到以下错误:

Error interpreting JPEG image file (Not a JPEG file: starts with 0x64 0x61).

如果我创建一个img并设置它的src= BLOB

, BLOB会正确显示下面包含的是BLOB的第一个片段:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAgGBgcGBQgHBwcJCQ

您的"Blob"实际上是一个数据URI:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

由于您只想要解码的数据部分,因此必须执行

file_put_contents(
    'image.jpg',
    base64_decode( 
        str_replace('data:image/jpeg;base64,', '', $blob)
    )
);

但是由于PHP本身支持data://流,你也可以这样做(感谢@NikiC)

file_put_contents('image.jpg', file_get_contents($blob));

如果上面的不起作用,你可以尝试使用GDlib:

imagejpg(
    imagecreatefromstring(
        base64_decode( 
            str_replace('data:image/jpeg;base64,', '', $blob)
        )
    ), 
    'image.jpg'
);

如果它真的是一个blob,您可能想尝试使用模式"wb"作为fopen()调用的第二个参数。

EDIT:您也可以考虑只使用file_put_contents(),它是二进制安全的。

如果是文件上传控件,$_POST将不包含该信息。你正在寻找用$_FILES处理文件上传。(更具体地说,move_uploaded_file)

给定新的更新,尝试以下操作:

  // 
  // Export a image blob to a file using either the specific image name
  // @blob     : The actual image blob
  // @fileName : Can be the explicit name (with an extension) or this can be
  //             just a generic file name and the extension (based on data
  //             type) will be appended automatically. This can also include
  //             path information.
  // Exmaples:
  //   storeBlob('data:image/png;base64,...', 'myimage');      ::  saves as myimage.png
  //   storeBlob('data:image/jpg;base64,...', 'img/new.jpg');  ::  saves as img/new.jpg
  function storeBlob($blob, $fileName)
  {
    $blobRE = '/^data:(('w+)'/('w+));base64,(.*)$/';
    if (preg_match($blobRE, $blob, $m))
    {
      $imageName = (preg_match('/'.'w{2,4}$/', $fileName) ? $fileName : sprintf('%s.%s', $fileName, $m[3]));
      return file_put_contents($imageName,base64_decode($m[4]));
    }
    return false; // error
  }

这个函数将数据uri保存到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;
}

你的用法:

// some_validation($_POST);
$filename = saveDataUri($_POST['logoImage']);
echo '<img src="' . $filename . '" alt="' . $filename . '" />';