Ejemplo n.º 1
0
 protected function get_image($url, $fp)
 {
     $filepath = $fp;
     // get image from the external source
     // set number of max. trials to load image
     $trials = 1;
     $ch = new CCURL($url, false);
     $currentTry = $trials;
     $content = null;
     $HTTPStatus = 0;
     while ($HTTPStatus != 200 && $currentTry > 0) {
         if ($currentTry != $trials) {
             usleep(100);
         }
         // wait for any subsequent try
         $currentTry--;
         $ch->createCurl();
         $HTTPStatus = $ch->getHttpStatus();
     }
     if ($HTTPStatus == 200) {
         $headers = $ch->getHeaders();
         $content_type = false;
         // default content type
         // look for image header
         foreach ($headers as $header) {
             if (substr($header, 0, 19) == 'Content-Type: image') {
                 $content_type = $header;
                 break;
             }
         }
         // traversing headers
         if (!$content_type) {
             // the content is not image
             $content = null;
         } else {
             $content = $ch->__tostring();
             if (strlen($content) > 400000) {
                 //image too big (> 400 KB)
                 // resize
                 $img_orig = imagecreatefromstring($content);
                 if ($img_orig == FALSE) {
                     return FALSE;
                 }
                 $orig_x = imagesx($img_orig);
                 $orig_y = imagesy($img_orig);
                 $new_x = 325;
                 $new_y = $orig_y * $new_x / $orig_x;
                 $img_new = imagecreatetruecolor($new_x, $new_y);
                 imagecopyresized($img_new, $img_orig, 0, 0, 0, 0, $new_x, $new_y, $orig_x, $orig_y);
                 // save resized image
                 imagejpeg($img_new, $filepath);
                 // clear mem
                 imagedestroy($img_new);
                 imagedestroy($img_orig);
             } else {
                 // save image as is
                 file_put_contents($filepath, $content);
             }
         }
     }
     // if status 200
 }