SimpleImage::best_fit PHP Method

best_fit() public method

Shrink the image proportionally to fit inside a $width x $height box
public best_fit ( integer $max_width, integer $max_height ) : SimpleImage
$max_width integer
$max_height integer
return SimpleImage
    function best_fit($max_width, $max_height)
    {
        // If it already fits, there's nothing to do
        if ($this->width <= $max_width && $this->height <= $max_height) {
            return $this;
        }
        // Determine aspect ratio
        $aspect_ratio = $this->height / $this->width;
        // Make width fit into new dimensions
        if ($this->width > $max_width) {
            $width = $max_width;
            $height = $width * $aspect_ratio;
        } else {
            $width = $this->width;
            $height = $this->height;
        }
        // Make height fit into new dimensions
        if ($height > $max_height) {
            $height = $max_height;
            $width = $height / $aspect_ratio;
        }
        return $this->resize($width, $height);
    }

Usage Example

Beispiel #1
0
 /**
  * Создание новости
  */
 public function create()
 {
     if (!User::isAdmin()) {
         App::abort('403');
     }
     if (Request::isMethod('post')) {
         $news = new News();
         $news->category_id = Request::input('category_id');
         $news->user_id = User::get('id');
         $news->title = Request::input('title');
         $news->slug = '';
         $news->text = Request::input('text');
         $image = Request::file('image');
         if ($image && $image->isValid()) {
             $ext = $image->getClientOriginalExtension();
             $filename = uniqid(mt_rand()) . '.' . $ext;
             if (in_array($ext, ['jpeg', 'jpg', 'png', 'gif'])) {
                 $img = new SimpleImage($image->getPathName());
                 $img->best_fit(1280, 1280)->save('uploads/news/images/' . $filename);
                 $img->best_fit(200, 200)->save('uploads/news/thumbs/' . $filename);
             }
             $news->image = $filename;
         }
         if ($news->save()) {
             if ($tags = Request::input('tags')) {
                 $tags = array_map('trim', explode(',', $tags));
                 foreach ($tags as $tag) {
                     $tag = Tag::create(['name' => $tag]);
                     $tag->create_news_tags(['news_id' => $news->id]);
                 }
             }
             App::setFlash('success', 'Новость успешно создана!');
             App::redirect('/' . $news->category->slug . '/' . $news->slug);
         } else {
             App::setFlash('danger', $news->getErrors());
             App::setInput($_POST);
         }
     }
     $categories = Category::getAll();
     App::view('news.create', compact('categories'));
 }
All Usage Examples Of SimpleImage::best_fit