I'm trying to upload my files as circles, but I can't make it work. I've seen some topics about applying a mask to the image, but when I apply the mask it takes way to long and the server shuts the request down.
I'm using the Intervention Image
library for Laravel
My code is as follows:
$identifier = "{$this->loggedUser->id}" . str_random(9) . ".{$file->getClientOriginalExtension()}";
$mask = $this->createCircleMask(200, 200);
$thumbMask = $this->createCircleMask(40, 40);
Image::make($file->getRealPath())->mask($mask)->save(public_path("images/profile/{$identifier}"));
Image::make($file->getRealPath())->mask($thumbMask)->save(public_path("images/profile/thumbs/{$identifier}"));
The createCircleMask
method looks like this:
public function createCircleMask($width, $height)
{
$circle = Image::canvas($width, $height, '#000000');
return $circle->circle($width - 1, $width / 2, $height / 2);
}
Here is a function that works in my case. But ONLY if I use the imagick driver. The standard gd library is very very slow, at least on my test computer. You can have a look at vendor\intervention\image\src\Intervention\Image\Gd\Commands\MaskCommand.php to find out why.
public function upload() {
$path = storage_path('app')."/";
$image = \Image::make(\Input::file('image'));
$image->encode('png');
/* if you want to have a perfect and complete circle using the whole width and height the image
must be shaped as as square. If your images are not guaranteed to be a square maybe you could
use Intervention's fit() function */
// $image->fit(300,300);
// create empty canvas
$width = $image->getWidth();
$height = $image->getHeight();
$mask = \Image::canvas($width, $height);
// draw a white circle
$mask->circle($width, $width/2, $height/2, function ($draw) {
$draw->background('#fff');
});
$image->mask($mask, false);
$image->save($path."circled.png");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With