【问题标题】:PHP create image from application/octet streamPHP从应用程序/八位字节流创建图像
【发布时间】:2011-08-22 00:13:24
【问题描述】:

我的应用程序正在使用内容类型“application/octet-stream”的移动设备向其发送图像。

我需要使用 GD 库处理这些图像,这意味着我需要能够从数据中创建图像对象。

通常,我一直在使用 imagecreatefromjpeg、imagecreatefrompng、imagecreatefromgif 等来处理从 Web 表单上传的文件,但是当我以 application/octet-stream 的形式出现时,这些似乎不起作用。

关于如何实现我的目标有什么想法吗?

编辑

这是我用来创建图像标识符的代码...我的处理程序在我的网站中完美运行,我可以分辨出我的网站和来自 iOS 的数据之间的唯一区别是内容类型

public function open_image($path) {
        # JPEG:
        $im = @imagecreatefromjpeg($path);
        if ($im !== false) { $this->image = $im; return $im; }

        # GIF:
        $im = @imagecreatefromgif($path);
        if ($im !== false) { $this->image = $im; return $im; }

        # PNG:
        $im = @imagecreatefrompng($path);
        if ($im !== false) { $this->image = $im; return $im; }

        $this->error_messages[] = "Please make sure the image is a jpeg, a png, or a gif.";
        return false;
    }

【问题讨论】:

  • MIME 类型对于 GD 处理数据的方式应该没有意义。显示你正在使用的代码
  • +1 请向我们展示您正在使用的代码。
  • 我把代码扔了,谢谢:)

标签: php image gd content-type


【解决方案1】:

简单:)

$image = imagecreatefromstring( $data );

具体来说:

$data = file_get_contents($_FILES['myphoto']['tmp_name']);
$image = imagecreatefromstring( $data );

【讨论】:

  • 嘿AAA,$data 是否可以简单地以 $_FILES['myphoto']['tmp_name'] 的形式找到?
  • @johnnietheblack - 不完全是,但足够接近:$image = imagecreatefromstring( file_get_contents($_FILES['myphoto']['tmp_name']) );
  • 啊,这是有道理的......所以 tmp 文件基本上只是一个“文本文件”,里面有字符串? (我显然对这方面的数据处理很陌生)
  • @johnnietheblack - tmp 文件可能是二进制文件(除非上传的图像是 SVG),file_get_contents() 只是获取数据。 'tmp_file' 部分只包含存储在服务器上的文件名。您可以使用:echo '<pre>'.print_r($_FILES,true).'</pre>;
【解决方案2】:

我在 codeigniter 论坛中发现了一种更改 mime 的方法,它可以工作,我想你也可以用于其他框架,这是 link,这是代码:

//if mime type is application/octet-stream (psp gives jpegs that type) try to find a   more specific mime type

$mimetype = strtolower(preg_replace("/^(.+?);.*$/", "\\1", $_FILES['form_field']  ['type'])); //reg exp copied from CIs Upload.php

if($mimetype == 'application/octet-stream'){
    $finfo = finfo_open(FILEINFO_MIME, '/usr/share/file/magic');
    if($finfo){
    $_FILES['form_field']['type'] = finfo_file($finfo, $_FILES['form_field']['tmp_name']);
    finfo_close($finfo);
    }
    else echo "finfo_open() returned false");
}  

需要在服务器上安装 Fileinfo 扩展。

它对我有用。

【讨论】:

    【解决方案3】:

    你也可以使用这个功能。它不需要任何其他依赖项。也适用于其他类型。

    function _getmime($file){
        if($info = @getimagesize($file)) {
            return image_type_to_mime_type($info[2]);
        } else {
            return mime_content_type($file);
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 2015-06-01
      • 2011-06-15
      • 2017-10-21
      相关资源
      最近更新 更多