从PHP写入映像文件时出错 [英] Error in Writing to Image file from PHP

查看:298
本文介绍了从PHP写入映像文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to write to an image file from a 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中,我收到以下错误:

In the previous code snippet, $_POST['logoImage'] is a BLOB. The file is correctly written to the root directory, however the file cannot be opened. In ubuntu 11.04 I receive the following error:

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

如果我创建一个img并设置其src = blob

The BLOB does correctly display if I create an img and set its src=blob

下面是BLOB的第一个片段:

Included below is the first snippet of the BLOB:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAgGBgcGBQgHBwcJCQ


推荐答案

你的Blob实际上是数据URI

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

由于你只需要解码数据部分,你必须这样做

Since you only want the decoded data part, you have to do

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

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

But since PHP natively supports data:// streams, you can also do (thanks @NikiC)

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

如果上述方法不起作用,您可以尝试使用GDlib:

If the above doesnt work, you can try with GDlib:

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

这篇关于从PHP写入映像文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆