【问题标题】:PHP createimagefromjpeg() How to include all image typesPHP从jpeg()创建图像如何包含所有图像类型
【发布时间】:2014-03-26 17:35:45
【问题描述】:

有没有一种方法可以使用 createimagefromjpeg() 从 url 保存图像但允许所有图像文件类型?

很明显 createimagefromjpeg 只允许 jpeg / jpg。

这是我目前的流程:

    // create the image and save it
    $imagefile = iageURL;
    $resource = imagecreatefromjpeg($imagefile);
    // X amount of quality is the last number
    imagejpeg($resource, "images/covers/imagename.jpeg", 50);
    imagedestroy($resource);

这很好用,因为它可以让我降低图像质量。但是当我尝试使用除 jpeg / jpg 以外的任何东西时出现错误。

有没有办法解决这个问题?或者也许是从 url 保存图像(以降低质量)的更好方法。

克雷格。

【问题讨论】:

    标签: php image png jpeg imagecreatefrompng


    【解决方案1】:

    您需要检查文件类型 - 如果可以,最好的方法是检查 MIME 类型,然后您可以进行切换并使用 GD lib 中的其他图像创建功能,例如 imagecreatefromgif()imagecreatefrompng() 等:

    switch($mime_type) {
        case 'image/jpeg':
        case 'image/jpg':
            $img = imagecreatefromjpeg($filename);
            break;
        case 'image/png':
            $img = imagecreatefrompng($filename);
            break;
        case 'image/gif':
            $img = imagecreatefromgif($filename);
            break;
    }
    

    另一种选择是将图像的数据抓取到字符串中并使用imagecreatefromstring() 从原始数据创建图像句柄:

    $filename = 'http://yoursite.com/yourlogo.jpg';
    $img = imagecreatefromstring(file_get_contents($filename));
    

    From the manual:These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

    【讨论】:

    • 完美,只需将函数更改为 imagecreatefromtstring() 即可。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2012-05-10
    相关资源
    最近更新 更多