php 使用 file_get_contents 从 url 获取图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12580056/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:51:19  来源:igfitidea点击:

Fetch image from url using file_get_contents

phploopsheaderlogicfile-get-contents

提问by swapnesh

This is my php code which is only fetching the first image out of 9, although when i check the URL manually all 9 image URL formed correctly, i tried this code with CURL too, but loop is not working, let me know what I am doing wrong ?

这是我的 php 代码,它只获取 9 个图像中的第一个图像,尽管当我手动检查 URL 时,所有 9 个图像 URL 都正确形成,我也用 CURL 尝试了这段代码,但循环不起作用,让我知道我是什么做错了吗?

<?php

for($i=2 ; $i <= 10 ; $i++ ){
header('Content-type: image/jpeg;');
$url = "http://www.lafourchette.com/p-3.3.0/default/rate-bar-bg-".$i.".jpg";
$mycontent = file_get_contents($url);
echo $mycontent;
}

回答by h2ooooooo

@h2ooooooo actually bro im not looking for a single image ... i just want to save this 9 images in a folder

@h2oooooooo 实际上兄弟我不是在寻找单个图像...我只想将这 9 个图像保存在一个文件夹中

<?php
    for ($i = 2 ; $i <= 10; $i++) {
        $imageName = "rate-bar-bg-" . $i . ".jpg";
        $imageContent = file_get_contents("http://www.lafourchette.com/p-3.3.0/default/" . $imageName);
        file_put_contents($imageName, $imageContent);
    }
?>

回答by Ja?ck

This is because it's not possible to concatenate JPEG images like that. The client will read the first image and treat the other images as trailing garbage.

这是因为不可能像这样连接 JPEG 图像。客户端将读取第一个图像并将其他图像视为尾随垃圾。

If you want to create one big image, you should use GDor imagick.

如果你想创建一个大图像,你应该使用GDimagick

Alternatively, you can create multiple images on the page that each point to rate-bar-bg-2.jpgthru 10. This is likely to be more efficient, unless you have very good reasons not to link to that website directly.

另外,您也可以在页面的每个点上创建多个图像rate-bar-bg-2.jpg10。这可能会更有效率,除非您有充分的理由不直接链接到该网站。

Or, just do the work once and create a sprite manually.

或者,只需完成一次工作并手动创建一个精灵。

回答by swapnesh

With the help of @h2ooooooo i came up with the solution ---

在@h2oooooooo 的帮助下,我想出了解决方案 ---

<?php

for($i=2 ; $i <= 10 ; $i++ ){
$filename = "rate-bar-bg-".$i.".jpg";
header('Content-type: image/jpeg;');
$url = "http://www.lafourchette.com/p-3.3.0/default/rate-bar-bg-".$i.".jpg";
$fileContent = file_get_contents($url);
file_put_contents($filename, $fileContent);
}

回答by Roel Veldhuizen

Set the content lenght as well

设置内容长度

header('Content-Length: ' . $size);

header('Content-Length: ' . $size);

回答by Mohit Bumb

  for ($i = 2 ; $i <= 10; $i++) {
        $imageName = "rate-bar-bg-" . $i . ".jpg";
        copy("http://www.lafourchette.com/p-3.3.0/default/" . $imageName,$imageName);
}