将图像直接保存到 PHP 中的目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15117303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving image straight to directory in PHP?
提问by Ghigo
I have an image file. Example: http://images5.fanpop.com/image/photos/31100000/random-random-31108109-500-502.jpg
我有一个图像文件。示例:http: //images5.fanpop.com/image/photos/31100000/random-random-31108109-500-502.jpg
I want to save the image to a directory called images-folder in my host. What would be the best way to do this using PHP?
我想将图像保存到主机中名为 images-folder 的目录中。使用 PHP 执行此操作的最佳方法是什么?
回答by
Yes, it is very simple. Here is a little cURLscript to do just that:
是的,这很简单。这是一个小的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);
This should do what you want. It will save the image to the directory and then name the image as random-random-31108109-500-502<-filename .jpg<-extension.
这应该做你想做的。它将图像保存到目录中,然后将图像命名为random-random-31108109-500-502<-filename .jpg<-extension。
回答by Ghigo
回答by AmazingDreams
Here is another, somewhat easier to follow, example, straight from the site I commented
这是另一个更容易理解的例子,直接来自我评论的网站
$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/
http://www.edmondscommerce.co.uk/php/php-save-images-using-curl/

