用php怎么都无法获取完整的图片,但是浏览器是可以正常打开的。
- <?php
- function displayImage($url) {
- // 重试次数
- $maxRetries = 3;
- $retryCount = 0;
- do {
- // 初始化cURL
- $ch = curl_init($url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 设置超时时间
- curl_setopt($ch, CURLOPT_FAILONERROR, true);
- // 获取图片内容
- $imageContent = curl_exec($ch);
- // 获取HTTP状态码
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $curlError = curl_error($ch);
- curl_close($ch);
- if ($httpCode === 200) {
- break; // 成功下载,退出循环
- }
- $retryCount++;
- } while ($retryCount < $maxRetries);
- if ($httpCode !== 200) {
- echo "无法获取图片内容。HTTP状态码: " . $httpCode . " 错误: " . $curlError;
- return;
- }
- // 获取图片的MIME类型
- $imageInfo = getimagesizefromstring($imageContent);
- if ($imageInfo === FALSE) {
- echo "无法识别图片格式。";
- return;
- }
-
- $mimeType = $imageInfo['mime'];
- // 设置适当的Content-Type头
- header("Content-Type: $mimeType");
- // 显示图片
- echo $imageContent;
- }
- // 调用函数显示图片
- displayImage("http://thumb.zgjiemeng.com/d/file/contents/2019/10/5da985cd42edd.jpg");
- ?>
复制代码 |