草庐IT

php - 为什么 PHP 在加载从 facebook 获取的图像时无法生成图像?

coder 2024-04-06 原文

几年前,我编写了一个 PHP (ZEND) 模块,至今仍在我的一些项目中使用。该模块是在对 PHP 图像处理有相当基本的了解(即 copypasta)的情况下构建的,但除了在一种情况下外,工作起来很漂亮。

该模块从表中提取 blob 数据,将其解析为图像,使用 imagcopyresampled() 调整其大小,然后将生成的 .jpg 发送到浏览器,它被称为标准 Controller 操作。

它似乎在所有情况下都有效,除非原始图像是由用户从 facebook 保存的(即右键单击 facebook 图像查看器并下载到桌面,然后上传到客户端站点)。我自己对此进行了多次测试,并且能够复制它。通过 photoshop 重新保存时,我也能够上传相同的图像而没有遇到问题。

我怀疑 facebook 图像显示在文件中添加了某种额外的元数据,导致我的系统崩溃。

有解决办法吗?

PHP图片模块代码如下:

private function _buildImage($mode) {
    //Prepare the output image
    //Currently CROP and RESIZE are using different output onstruction calls
    //So $finalImage is initialized prior to entering the mode blocks.

    $finalImage = imagecreatetruecolor($this->_width, $this->_height);
    $backgroundFillColor = imagecolorallocate($finalImage, RED, BLUE, GREEN);

    imageFill($finalImage, 0, 0, $backgroundFillColor);

    $this->_table = $this->_getTable($mode);

    $image = $this->_request->image;
    $this->_imageData = $this->_table->fetchEntryAsRow($image);

    //Set top and left to 0 to capture the top/left corner of the orignal image.
    $top = 0;
    $left = 0;


    $inputImage = imagecreatefromstring(    $this->_imageData->image);
    list($inputWidth, $inputHeight) = $this->_getImageSize($this->_imageData->image);   

    //Ratio is the target ratio of $this->_width divided by $this->_height, as set in actions.
    //For index thumbnails this ratio is .7
    //For index large images this ratio is 2
    $ratio = $this->_width / $this->_height;


    //define offset width and offset height as being equal to input image width and height
    $offsetWidth = $inputWidth;
    $offsetHeight = $inputHeight;

    //Define Original Ratio as found in the image in the table.
    $inputRatio = $inputWidth / $inputHeight;

    //Rendering maths for RESIZE and CROP modes.
    //RESIZE forces the whole input image to appear within the frame of the output image.
    //CROP forces the output image to contain only the relevantly sized piece of the input image, measured from the middle.

    if($this->_mode == CROP) {
        if($inputRatio > $ratio) {
            //Original image is too wide, use $height as is. Modify $width;
            //define $scale: input is scaled to output along height.
            $scale = $inputHeight / $this->_height;
            //Calculate $left: an integer calculated based on 1/2 of the input width * half of the difference in the rations.
            $left = round(($inputWidth/2)*(($inputRatio-$ratio)/2), 0);
            $inputWidth = round(($inputWidth - ($left*2)), 0);
            $offset = $offsetWidth - $inputWidth;
        } else {
            //Original image is too high, use $width as is.  Modify $height;
            $scale = $inputWidth / $this->_width;
            $inputHeight = round(($this->_height * $scale),0);
            $offset = $offsetHeight - $inputHeight;
            $top = $offset / 2;
        }

        imagecopyresampled($finalImage, //Destination Image 
            $inputImage, //Original Image 
            0, 0, //Destination top left Coord 
            $left, $top, //Source top left coord
            $this->_width, $this->_height,  //Final location Bottom Right Coord
            $inputWidth, $inputHeight //Source bottom right coord.
        );

    } else {

        if($inputRatio < $ratio) {
            //Original image is too wide, use $height as is. Modify $width;

            $scale = $inputHeight / $this->_height;


            $calculatedWidth = round(($inputWidth / $scale), 0);
            $calculatedHeight = $this->_height;

            $offset = $this->_width - $calculatedWidth;
            $left = round(($offset / 2), 0);
            $top = 0;

        } else {
            //Original image is too high, use $width as is.  Modify $height;
            $scale = $inputWidth / $this->_width;
            $calculatedHeight = round(($inputHeight / $scale),0);
            $calculatedWidth = $this->_width;
            $offset = $this->_height - $calculatedHeight;
            $top = round(($offset / 2), 2);
        }

        imagecopyresampled($finalImage, //Destination Image 
            $inputImage, //Original Image 
            $left, $top, //Destination top left Coord 
            0, 0, //Source top left coord
            $calculatedWidth, $calculatedHeight,  //Final location Bottom Right Coord
            $inputWidth, $inputHeight //Source bottom right coord.
        );
    }



    imagejpeg($finalImage, null, 100);
    imagedestroy($inputImage);
    imagedestroy($finalImage);

}

我怀疑问题实际上可能出在 _getImageSize 的实现上。

private function _getImageSize($data)
{
    $soi = unpack('nmagic/nmarker', $data);
    if ($soi['magic'] != 0xFFD8) return false;
    $marker = $soi['marker'];
    $data   = substr($data, 4);
    $done   = false;

    while(1) {
            if (strlen($data) === 0) return false;
            switch($marker) {
                    case 0xFFC0:
                            $info = unpack('nlength/Cprecision/nY/nX', $data);
                            return array($info['X'], $info['Y']);
                            break;

                    default:
                            $info   = unpack('nlength', $data);
                            $data   = substr($data, $info['length']);
                            $info   = unpack('nmarker', $data);
                            $marker = $info['marker'];
                            $data   = substr($data, 2);
                            break;
            }
     }
}

您可以在 http://www.angelaryan.com/gallery/Image/22 查看此问题的另一个示例它显示一个蓝色方 block ,而不是存储在数据库中的图像。

最佳答案

上传后尝试自动“重新保存”图像

imagejpeg(imagecreatefromjpeg($filename),$filename,9);

这应该会根据原始 Facebook 图片重新创建任何格式错误或无法识别的 header 。

关于php - 为什么 PHP 在加载从 facebook 获取的图像时无法生成图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17903552/

有关php - 为什么 PHP 在加载从 facebook 获取的图像时无法生成图像?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  6. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  7. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  8. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  9. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  10. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

随机推荐