【问题标题】:Saving image straight to directory in PHP? [closed]将图像直接保存到 PHP 中的目录? [关闭]
【发布时间】:2017-04-07 23:39:20
【问题描述】:

我有一个图像文件。示例:http://images5.fanpop.com/image/photos/31100000/random-random-31108109-500-502.jpg

我想将图像保存到主机中名为 images-folder 的目录中。使用 PHP 执行此操作的最佳方法是什么?

【问题讨论】:

标签: php


【解决方案1】:

是的,很简单。这里有一个小cURL 脚本可以做到这一点:

$image_link = "http://images5.fanpop.com/image/photos/31100000/random-random-31108109-500-502.jpg";//Direct link to image
$split_image = pathinfo($image_link);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $image_link);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$response= curl_exec ($ch);
curl_close($ch);
$file_name = "images-folder/".$split_image['filename'].".".$split_image['extension'];
$file = fopen($file_name , 'w') or die("X_x");
fwrite($file, $response);
fclose($file);

这应该做你想做的事。它将图像保存到目录中,然后将图像命名为random-random-31108109-500-502.jpg

【讨论】:

  • 非常感谢...它的工作..
【解决方案2】:

这是另一个更容易理解的例子,直接来自我评论过的网站

$remote_img = 'http://www.somwhere.com/images/image.jpg';
$img = imagecreatefromjpeg($remote_img);
$path = 'images/';
imagejpeg($img, $path);

http://www.edmondscommerce.co.uk/php/php-save-images-using-curl/

【讨论】:

  • 请解释反对意见。
  • 我不明白为什么你的解决方案工作很好,我会投票给你,因为你的答案是真实的。
  • 您无需将文件作为图像读取即可下载图像。您正在分配所有内存并创建一个可编辑的图像缓冲区,其中包含与保存图像相关的所有开销。那将无法扩展。此外,您还通过要求 PHP 将远程文件解释为 JPEG 来引入安全风险。 libjpeg 漏洞利用并非未知。这些是我投反对票的原因。
【解决方案3】:

没有cURL就更简单了:

<?php
    $link= "http://images5.fanpop.com/image/photos/31100000/random-random-31108109-500-502.jpg";
    $destdir = 'images-folder/';
    $img=file_get_contents($link);
    file_put_contents($destdir.substr($link, strrpos($link,'/')), $img);
?>

【讨论】:

  • 使用这种方式会导致图片损坏无法打开
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-13
  • 2016-03-18
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2014-11-12
相关资源
最近更新 更多