简体   繁体   English

PHP处理MIME类型为application / x-gzip的图像

[英]PHP processing image with MIME type application/x-gzip

In my application I process links to various websites and download images that are present on those websites into my database. 在我的应用程序中,我处理到各种网站的链接,并将这些网站上存在的图像下载到我的数据库中。 I have trouble processing this image . 我在处理此图像时遇到麻烦。 It looks like it's JPEG, but imagecreatefromjpeg() returns an error 看起来像是JPEG,但imagecreatefromjpeg()返回错误

Not a JPEG file: starts with 0x1f 0x8b 不是JPEG文件:以0x1f 0x8b开头

I finally found working solution to get true file type, which is 我终于找到了工作解决方案来获取真实的文件类型,这是

$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));

which returns application/x-gzip; charset=binary 返回application/x-gzip; charset=binary application/x-gzip; charset=binary

I'm not sure what to do with that. 我不确定该怎么办。 I guess it's somehow cached into gzip and the browser can work with that and that's why the image is normally loaded inside browser. 我想它是以某种方式缓存到gzip中的,浏览器就可以使用它,这就是为什么通常在浏览器中加载图像的原因。 But what can be done in PHP to download that file into some usual image type file? 但是,用PHP可以将文件下载到一些常见的图像类型文件中怎么办? Thanks 谢谢

OK, I figured it out myself. 好吧,我自己弄清楚了。 This works 这有效

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

my working solution 我的工作解决方案

//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......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM