PHP处理图像与MIME类型的应用程序/x-gzip


PHP processing image with MIME type application/x-gzip

在我的应用程序中,我处理到各种网站的链接,并将这些网站上存在的图像下载到我的数据库中。我处理这个图像有困难。看起来像JPEG,但是imagecreatefromjpeg()返回一个错误

非JPEG文件:以0x1f 0x8b开头

我终于找到了工作的解决方案,以获得真正的文件类型,这是

$file = "http://www.inc.com/uploaded_files/image/lemonade-970_29794.jpg"
$file_info = new finfo(FILEINFO_MIME);
echo $file_info->buffer(file_get_contents($file));

返回application/x-gzip; charset=binary

我不知道该怎么办。我猜它以某种方式缓存在gzip中,浏览器可以使用它,这就是为什么图像通常加载在浏览器内。但如何在PHP中将该文件下载到一般的图像类型文件中呢?由于

好吧,我自己弄明白了。这是

$file = gzencode("http://www.inc.com/uploaded_files/image/lemonade-970_29794.jpg");
$image = imagecreatefromstring($file);

我的工作解决方案

//detect if gzip
function _is_gzip_jpeg($data){
  $gzip_check="'x1f'x8b";
      return substr( $data, 0, strlen($gzip_check) ) === $gzip_check;
}
//create tmp file
$local = tempnam("/tmp", "ic_");
//downloaded content
$content = file_get_contents($url);
//check if gzip
if(_is_gzip_jpeg($content)){
  //if yes, decode it and save.
  file_put_contents($local, gzdecode($content ));
}else{ 
  //not gzip content, save it to tmp file
  file_put_contents($local, $content );
}
//check meta
$meta = getimagesize($local);
//....get resource
if($meta['mime'] == 'image/jpeg') {
  $image = @imagecreatefromjpeg($local);
} else if ($meta['mime'] == 'image/png') {
  $image = @imagecreatefrompng($local);
} else if ($meta['mime'] == 'image/gif') {
  $image = @imagecreatefromgif($local);
}else{
  $image = @imagecreatefromjpeg($local);
}
//do what you need to do here......