【问题标题】:save any image type from a url as jpg将 url 中的任何图像类型保存为 jpg
【发布时间】:2012-10-20 13:30:02
【问题描述】:

是否可以将带有任何类型图像(可以是 jpg、png、gif 等)的 url 作为 jpg 保存到 php 中的文件夹中而无需多个步骤(检查扩展名,另存为相同类型并转换为 jpg )?

示例网址

  1. http://jdownloader.org/_media/knowledge/wiki/jdownloader.png?cache=&w=512&h=512 (.PNG)
  2. http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com (.jpg)

许多网址并不总是包含 imagename.ext 类型的结构。

对于这样的代码(从这里PHP save image file

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($url)); 

是否可以在不检查扩展名的情况下保存任何图像文件类型? 我试过了

$input = 'URL_string';
$output = 'path/to/folder/name'; // no extensions
file_put_contents($output, file_get_contents($url)); 
imagejpeg($output,"temp.jpg");

努力工作。我阅读了Create Image From Url Any File TypeSaving image from PHP URL 等等,但不确定如何获得简单的解决方案。

感谢您的帮助。

【问题讨论】:

    标签: php image save-as


    【解决方案1】:

    我想这是不可能的(考虑到所有现有的图像文件类型),但对于最基本的图像文件类型,应该有用于转换的库。

    对于您尝试过的事情 - 只是将文件扩展名重命名为 .jpg 实际上并不能使其成为 jpg(例如,IrfanView 在打开此类文件时会警告您并询问您是否要更改扩展名纠正一个)

    【讨论】:

    • 我只是尝试摆弄扩展,认为可能 imagejpeg() 会做到这一点。我看到了一些关于 imajik 的东西,但我没有安装它。在我继续添加包之前,希望 php 能做到这一点。
    【解决方案2】:

    作为您的问题的解决方案,请参考下面提到的代码 sn-p

    <?php
      $im=imagecreatefromjpeg('http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com');
        header('Content-type:image/jpeg');
        imagejpeg($im);
     ?>
    

    imagecreatefromjpeg 函数用于从文件或 URL 创建图像

    还必须在 php.ini 文件中将 allow_url_fopen 设置设置为 On 才能从 URL 创建图像

    更多详情请参考以下网址中提到的文档

    http://php.net/manual/en/filesystem.configuration.php

    【讨论】:

    • 它并不总是来自 jpg。它可以是任何文件类型。这就是我要找的。类似 imagejpeg('$url') 的东西,其中 url 可以是 jpg、png 或任何东西
    • 请尝试我的最新答案中提到的代码 sn-p 。它将保存独立于任何文件扩展名的图像。
    【解决方案3】:

    作为您的问题的解决方案,请参考下面提到的代码 sn-p

           $h=get_headers('http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com',1);
           $img_content=file_get_contents('http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com');
           $extension='jpg';
          if(!empty($img_content))
          {
        switch($h['Content-type'])
        {
        case 'image/jpeg':
            $extension='jpg';
            break;
        case 'image/gif':
            $extension='gif';
            break;
        case 'image/png':
            $extension='png';
            break;      
        }
    
    file_put_contents('abc.'.$extension,$img_content);
    
     }
    

    【讨论】:

    • 有一个编辑按钮。另外我猜他想将图像转换为 JPG,而不仅仅是更改扩展名。
    • 是的,不仅仅是扩展名的改变。但根据@Seth 所说,我无法在任何地方找到任何讨论的内容,我想我应该采用常规方式:检查标题,并使用诸如 createimagefromjpeg/png/gif 等单独的函数。
    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多