2017-06-04 33 views
3

假设我有一个最喜欢的方形尺寸,并且在这种情况下它具有2236 px宽度和高度。使用Laravel 5干涉图像为图像添加空白区域以制作方形图像

我需要使用php intervention package将我的图像保存在我的服务器上。

这不是重要的,什么是用户的图像尺寸,但问题是,图像必须保存新的大小,但用户图像必须是中心和中央广场的,如果画面小于我最喜欢的尺寸,它必须拉伸,如果图像更大,它必须压缩到我的尺寸

请看看这张照片: my plan

这些都是一些实际的例子: example 1 example 2

有谁在这种情况下,任何经验,你知不知道我该怎么做呢?

由于提前

+0

http://image.intervention.io/api/resizeCanvas – mkaatman

回答

1

好了,感谢@Anton他的暗示,我这样做是为了解决我的问题:

的图像是呈横长方形,垂直长方形或正方形。

我写这几行代码为每一种情况,并就我的情况的伟大工程

$img = Image::make($image->getRealPath()); 

    $width = $img->width(); 
    $height = $img->height(); 


    /* 
    * canvas 
    */ 
    $dimension = 2362; 

    $vertical = (($width < $height) ? true : false); 
    $horizontal = (($width > $height) ? true : false); 
    $square  = (($width = $height) ? true : false); 


    if ($vertical) { 
     $top = $bottom = 245; 
     $newHeight = ($dimension) - ($bottom + $top); 
     $img->resize(null, $newHeight, function ($constraint) { 
      $constraint->aspectRatio(); 
     }); 

    } else if ($horizontal) { 
     $right = $left = 245; 
     $newWidth = ($dimension) - ($right + $left); 
     $img->resize($newWidth, null, function ($constraint) { 
      $constraint->aspectRatio(); 
     }); 

    } else if ($square) { 
     $right = $left = 245; 
     $newWidth = ($dimension) - ($left + $right); 
     $img->resize($newWidth, null, function ($constraint) { 
      $constraint->aspectRatio(); 
     }); 

    } 

    $img->resizeCanvas($dimension, $dimension, 'center', false, '#ffffff'); 
    $img->save(public_path("storage/{$token}/{$origFilename}")); 
    /* 
    * canvas 
    */ 
1
<?php 
$width = 2236; 
$height = 2236; 

$img = Image::make('image.jpg'); 

// we need to resize image, otherwise it will be cropped 
if ($img->width() > $width) { 
    $img->resize($width, null, function ($constraint) { 
     $constraint->aspectRatio(); 
    }); 
} 

if ($img->height() > $height) { 
    $img->resize(null, $height, function ($constraint) { 
     $constraint->aspectRatio(); 
    }); 
} 

$img->resizeCanvas($width, $height, 'center', false, '#ffffff'); 
$img->save('out.jpg'); 
+0

感谢您的回复,但是这个剧本不改变原始图像的大小,只是将原始图像放在2236px的中心。 '而且,如果图像宽度小于'$ width',该怎么办? – Kiyarash

+0

@Kiyarash如果图片太小,会发生什么情况?你想伸展它吗? – Anton

+0

请您点击问题中的示例图片吗? – Kiyarash