I've got a bunch of image links I need to download locally on the server. Most requests works fine but every now and then when the job runs scheduled night time, it returns black images. The source is checked and gives the right image.
Rarely it also returns black images with the actual picture in the top left corner but very small.
The array contains about 150 images to get and resize.
First, I download the file:
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);
}
Then resize it:
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;
}
}
As follows:
foreach ($URLimages as &$value) {
if (strpos($value->image, '.jpg')) {
downloadFile($value->image, $path);
$test = basename($value->image);
$img = Img_Resize($path . $test);
}
}