我有一堆图像链接,我需要在服务器上本地下载。大多数请求工作正常,但偶尔当作业在预定的夜间运行时,它会返回黑色图像。检查源并给出正确的图像。
有时它也返回黑色图像,实际图片在左上角,但非常小。
数组包含大约150张图片,可以获取和调整大小。
首先,我下载文件:
function downloadFile($url, $path) {
$file = basename($url);
$source = file_get_contents($url);
$fp = fopen($path. $file, 'w');
set_time_limit(0);
$options = array(
CURLOPT_FILE => $fp,
CURLOPT_TIMEOUT => 28800,
CURLOPT_URL => $fp,
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
fwrite($fp, $source);
fclose($fp);
curl_close($ch);
}
然后调整大小:
function Img_Resize($path) {
$x = getimagesize($path);
$width = $x['0'];
$height = $x['1'];
$rs_width = 245;//resize to half of the original width.
$rs_height = 163;//resize to half of the original height.
switch ($x['mime']) {
case "image/gif":
$img = imagecreatefromgif($path);
break;
case "image/jpeg":
$img = imagecreatefromjpeg($path);
break;
case "image/jpg":
$img = imagecreatefromjpeg($path);
break;
case "image/png":
$img = imagecreatefrompng($path);
break;
}
$img_base = imagecreatetruecolor($rs_width, $rs_height);
imagesetinterpolation($img_base, IMG_BICUBIC);
imagecopyresampled($img_base, $img, 0, 0, 0, 0, $rs_width, $rs_height, $width, $height);
$path_info = pathinfo($path);
switch ($path_info['extension']) {
case "gif":
imagegif($img_base, $path);
break;
case "jpeg":
imagejpeg($img_base, $path);
break;
case "jpg":
imagejpeg($img_base, $path);
break;
case "png":
imagepng($img_base, $path);
break;
}
}
如下:
foreach ($URLimages as &$value) {
if (strpos($value->image, '.jpg')) {
downloadFile($value->image, $path);
$test = basename($value->image);
$img = Img_Resize($path . $test);
}
}
downloadFile似乎假设一切'只是工作'。生活和编程不是这样的。
下面是一些我预计可能出现错误并在发生错误时采取措施的区域。如果你愿意,你也可以用其他的方法来完成,比如使用try…捕获和抛出异常。
$source = file_get_contents($url);
if (!$source) { // failed - retry or take other action
return false;
}
$fp = fopen($path. $file, 'w');
if (!$fp) { // file didn't open ...
return false;
}
$ch = curl_init();
if (!$ch) { // curl session didn't start ...
return false;
}
if (!curl_exec( $ch)) { // curl session didn't work
return false;
}
if (!fwrite($fp, $source)) { // data didn't get written to file
return false;
}
// return success
return true;
}
您的主代码不应该尝试为下载失败生成图像:
foreach ($URLimages as &$value) {
if (strpos($value->image, '.jpg')) {
if (downloadFile($value->image, $path)) {
$test = basename($value->image);
$img = Img_Resize($path . $test);
}
}
}
您确定您正在使用CURLOPT_TIMEOUT而不是CURLOPT_TIMEOUT_MS吗?
28800秒的超时时间似乎很高。如果您在另一个地方将CURLOPT_TIMEOUT_MS设置为较低的值,则取最低的值。
当下载文件的时间超过你的超时时间,你会得到一个不完整的文件…