Exemple #1
0
function resize_image($filename, $destfile = null, $width = 600, $quality = 90)
{
    try {
        require_once dirname(__DIR__) . '/Util/ImageResize.php';
        $img = new Eventviva\ImageResize($filename);
        $img->quality_jpg = $quality;
        if ($img->getSourceWidth() > $img->getSourceHeight()) {
            if ($img->getSourceWidth() < $width) {
                if ($destfile == $filename) {
                    return false;
                }
            } else {
                $img->resizeToWidth($width);
            }
        } else {
            if ($img->getSourceHeight() < $width) {
                if ($destfile == $filename) {
                    return false;
                }
            } else {
                $img->resizeToHeight($width);
            }
        }
        if ($destfile === null) {
            $destfile = $filename;
        }
        $img->save($destfile);
        return true;
    } catch (Exception $e) {
    }
    return false;
}
Exemple #2
0
 /**
  * Adding file to local directory
  * 
  * @array $arFields('path_from', 'path_to', 'width', 'height')
  */
 public static function add($arFields)
 {
     if (file_exists($arFields["path_from"])) {
         if (!empty($arFields["path_to"]) && file_exists($arFields["path_to"])) {
             return;
         }
         //print_r($arFields);
         $image = new \Eventviva\ImageResize($arFields["path_from"]);
         list($width, $height, $type, $attr) = getimagesize($arFields["path_from"]);
         if ($arFields["width"] && $arFields["height"] && ($arFields["width"] != $width || $arFields["height"] != $height)) {
             $image->crop($arFields["width"], $arFields["height"]);
         }
         if (!$arFields["path_to"]) {
             $path_parts = pathinfo($arFields["path_from"]);
             $file_name = $path_parts["filename"];
             $image->save($_SERVER["DOCUMENT_ROOT"] . "/upload/epg/" . $file_name . ".jpg");
         } else {
             $image->save($arFields["path_to"]);
         }
     }
 }
function generatethumb($src, $destination, $newwidth, $newheight)
{
    $image = new \Eventviva\ImageResize($src);
    $image->resize($newwidth, $newheight, 1);
    $image->save($destination);
}
Exemple #4
0
        $post['author'] = 'none';
    }
    $errors = array();
    if (!empty($_POST['file'])) {
        $dataURL = $_POST['file'];
        $data = explode(',', $dataURL)[1];
        $data = base64_decode($data);
        $file = uniqid();
        $name = preg_replace("/\\.[^.\\s]{3,4}\$/", "", $file);
        $location = WWW_ROOT . 'uploads/images/' . $_POST['content'];
        $success = file_put_contents($location, $data);
        $upload = $pinDAO->insert($post);
        if (!empty($upload)) {
            $image = new Eventviva\ImageResize($location);
            $image->resizeToWidth(800);
            $image->save(WWW_ROOT . 'uploads/images/' . 'large_' . $_POST['content']);
            $image->resizeToWidth(300);
            $image->save(WWW_ROOT . 'uploads/images/' . $_POST['content']);
            echo json_encode($upload);
        }
    } else {
        echo json_encode($pinDAO->insert($post), JSON_NUMERIC_CHECK);
    }
});
$app->get('/pins/tags/?', function () use($pinDAO) {
    header("Content-Type: application/json");
    echo json_encode($pinDAO->selectTagsById($_SESSION['user']['id']), JSON_NUMERIC_CHECK);
    exit;
});
$app->get('/pins/tags/:tag/?', function ($tag) use($pinDAO) {
    header("Content-Type: application/json");
Exemple #5
0
function download($url, $store_dir)
{
    $filename = get_image_filename($url, $store_dir);
    if (file_exists($filename)) {
        return;
    }
    //存在时不下载
    $curl = new Curl\Curl();
    $curl->setHeader('X-Requested-With', 'XMLHttpRequest');
    $curl->setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:40.0) Gecko/20100101 Firefox/40.0');
    $curl->setHeader('Accept-Language', 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3');
    $curl->setHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
    @mkdir($store_dir, 0755, true);
    $curl->get($url);
    $data = $curl->response;
    file_put_contents($filename, $data);
    try {
        $image = new \Eventviva\ImageResize($filename);
        $image->resizeToWidth(JS_IMG_WIDTH);
        $image->save($filename);
    } catch (Exception $e) {
    }
    return $filename;
}
$app->get('/images/{offset:[0-9]+}/{limit:[0-9]+}', function ($offset, $limit) use($response) {
    $robots = Images::find(['offset' => $offset, 'limit' => $limit]);
    $data = [];
    foreach ($robots as $robot) {
        $data[] = $robot;
    }
    $response->setJsonContent($data);
});
$app->get('/img_resize/{id:[0-9]+}', function ($id) use($app, $response) {
    $image = Images::findFirstById($id);
    if (count($image) > 0) {
        $resized_file = str_replace('http://hack4dk.dr.dk/', '/home/ubuntu/workspace/resized_images/', $image->url);
        $percent = 0.2;
        if (!file_exists($resized_file)) {
            //Lets create folder structure if it doesn't exist
            if (!file_exists(dirname($resized_file))) {
                mkdir('./' . dirname($resized_file), '0777', true);
            }
            $image = new \Eventviva\ImageResize($image->url);
            $image->resizeToWidth(800);
            $image->save($resized_file);
        }
        //echo 'her' . $resized_file;
        $response->setHeader('Content-Type', 'image/jpeg');
        $response->send();
        readfile($resized_file);
    }
    $response->setJsonContent(['could not load image!']);
});
$app->handle();
$response->send();
Exemple #7
0
 function handleAddPhoto($request)
 {
     if (isset($request['photoUrl'])) {
         try {
             // create thumb
             if (!file_exists('./photos/' . $this->currentUser->userid . '/thumbs')) {
                 mkdir('./photos/' . $this->currentUser->userid . '/thumbs', 0777, TRUE);
             }
             $image = new \Eventviva\ImageResize('./photos/' . $this->currentUser->userid . '/' . $request['photoUrl']);
             $image->resizeToHeight(1080);
             $image->save('./photos/' . $this->currentUser->userid . '/' . $request['photoUrl'], null, 90);
             $image->resizeToHeight(200);
             $image->save('./photos/' . $this->currentUser->userid . '/thumbs/' . $request['photoUrl']);
             //end create thumb
             try {
                 $this->storePhotoToDB($request);
             } catch (Exception $e) {
                 //var_dump($e);
                 $_SESSION['message'] = 'Fail to store photo ' . $request['photoUrl'] . ' into the database. : ' . $e->getMessage();
                 $_SESSION['messageStatus'] = 'error';
                 exit;
             }
             $_SESSION['message'] = 'Image ' . $request['photoUrl'] . ' added to db and thumbnail created';
             $_SESSION['messageStatus'] = 'success';
         } catch (Exception $e) {
             // var_dump($e);
             // exit();
             $_SESSION['message'] = 'Fail to create thumbnail for Image ' . $request['photoUrl'];
             $_SESSION['messageStatus'] = 'error';
         }
     } else {
         $_SESSION['message'] = 'No photoUrl given';
         $_SESSION['messageStatus'] = 'error';
     }
 }
 private static function createThumb($source, $target)
 {
     include_once getcwd() . '/scripts/external/ImageResize.php';
     $image = new \Eventviva\ImageResize($source);
     $image->resize(100, 75);
     $image->save($target);
 }
    public function action_new()
    {
        session_start();
        // Сохраняем введенные в форму данные
        $title = $_POST['title'];
        $content = $_POST['content'];

        // Если пользователь не авторизован - отправляем на форму авторизации.
        if (!empty($_SESSION))
        {
            // Загрузчик изображений
            if (is_uploaded_file($_FILES['image']['tmp_name']))
            {

                // Проверки загружаемого файла
                $check = new Add;
                $error = $check->check_img($_FILES);

                // Если проверки пройдены - перекидываем на сервер
                if(empty($error))
                {
                    // Получаем расширение загруженного файла
                    $extension = strtolower(substr(strrchr($_FILES['image']['name'], '.'), 1));

                    //собираем путь к папке с изображениями
                    $path = __DIR__ . '/../upload/news_img';

                    // Генерируем уникальное имя файла с этим расширением
                    $filename = $check->getRandomFileName($path, $extension);

                    // Собираем полный адрес с новым именем
                    $target = $path . '/' . $filename . '.' . $extension;

                    // Запоминаем в сессию имя файла
                    $_SESSION['img_name'] = $filename . '.' . $extension;

                    // Сохраняем изображение на сервере с ресайзом 650х650
                    $image = new \Eventviva\ImageResize($_FILES['image']['tmp_name']);
                    $image->resizeToBestFit(650, 650);
                    $image->save($target);

                    // Собираем путь до миниатюр
                    $path2 = __DIR__ . '/../upload/news_img/250x250';
                    $target2 = $path2 . '/' . $filename . '.' . $extension;

                    // Делаем и сохраняем миниатюры
                    $image = new \Eventviva\ImageResize($target);
                    $image->resizeToBestFit(300, 300);
                    $image->save($target2);
                }

                // Если нет - выводим ошибку
                else
                {
                    $data['errors'] = $error;
                }



                // Данные для js
                $res = '<script type="text/javascript">';
                $res .= "var data = new Object;";
                foreach($data as $key => $value)
                {
                    $res .= 'data.'.$key.' = "'.$value.'";';
                }
                $res .= 'window.parent.handleResponse(data);';
                $res .= "</script>";
                echo $res;
            }

            // Если обе формы заполнены - обрабатываем данные
            if (!empty($_POST['title']) && !empty($_POST['content']))
            {
                // Готовим данные для добавления в БД
                $article = new Add;
                $article->title = $_POST['title'];
                $article->content = $_POST['content'];
                $article->date = date('d.m.Y H:i');
                $article->userName = $_SESSION['user'];

                // Проверяем загружалась ли картинка
                if (!empty($_SESSION['img_name']))
                {
                    $article->img_name = $_SESSION['img_name'];
                    unset($_SESSION['img_name']);
                }

                // Сохраняем все данные в базу
                $article->save();
                ?>

                <script type="text/javascript">
                alert( "Ваше объявление было отправлено на проверку модератору, оно появится на сайте в самое ближайшее время." );
                </script>

                <?
            }

            //Выводим ошибку если одно из полей пустое
            else if (empty($_POST['title']) xor empty($_POST['content']))
            {
                $this->error = 'Заполните все поля!';
            }
            require_once __DIR__ . '/../views/add_views.php';
        }

        // Отправляем на форму авторизации
        else
        {
            $this->error = 'Добавлять объявленя могут только зарегистрированные пользователи.
            Пожалуйста зарегистрируйтесь или зайдите под своим логином.';

            include_once __DIR__ . '/../views/login_views.php';
        }
    }
 /**
  * Generates and stores a cached copy of this thumbnail
  */
 public function generate()
 {
     $image = new Eventviva\ImageResize($this->getOriginalUrl());
     $image->resizeToWidth($this->_size);
     $image->save($this->_cache->getCachePath() . DIRECTORY_SEPARATOR . $this->getFilename(), IMAGETYPE_JPEG);
 }