Skip to content

Commit

Permalink
Add masking to PictureBox
Browse files Browse the repository at this point in the history
  • Loading branch information
simonhamp committed Jan 15, 2024
1 parent e364676 commit ba1a78f
Showing 1 changed file with 67 additions and 7 deletions.
74 changes: 67 additions & 7 deletions src/Layout/PictureBox.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,87 @@

namespace SimonHamp\TheOg\Layout;

use Intervention\Image\Drivers\Imagick\Modifiers\PlaceModifier;
use Intervention\Image\Image;
use Imagick;
use ImagickDraw;
use ImagickPixel;
use Intervention\Image\ImageManager;
use Intervention\Image\Interfaces\ImageInterface;

readonly class PictureBox extends Box
class PictureBox extends Box
{
public string $path;

/**
* @var array<callable<Imagick>>
*/
public array $maskQueue;

protected ImageInterface $picture;

public function render(ImageInterface $image): void
{
$picture = ImageManager::imagick()
->read(file_get_contents($this->path))
->cover($this->box->width(), $this->box->height());
if (! empty($this->maskQueue)) {
foreach ($this->maskQueue as $mask) {
$this->mask($mask());
}
}

$position = $this->calculatePosition();

$image->place(
element: $this->getPicture(),
offset_x: $position->x(),
offset_y: $position->y()
);
}

/**
* Apply a mask image to the picture
*/
public function mask(Imagick $mask): void
{
$base = $this->getPicture()->core()->native();

$base->setImageMatte(true);

$base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0);

$base->writeImage(__DIR__.'/../../circle.png');
}

public function circle(): static
{
$this->maskQueue[] = function () {
$width = $this->box->width();
$start = intval(floor($width / 2));

// Create the circle
$circle = new ImagickDraw();
$circle->setFillColor(new ImagickPixel('#fff'));
$circle->circle($start, $start, $start, $width - 10);

// Draw it to an Imagick instance
$image = new Imagick();
$image->newImage($width, $width, 'none', 'png');
$image->setImageMatte(true);
$image->drawImage($circle);

return $image;
};

$image->place($picture);
return $this;
}

public function path(string $path): self
{
$this->path = $path;
return $this;
}

protected function getPicture(): ImageInterface
{
return $this->picture ??= ImageManager::imagick()
->read(file_get_contents($this->path))
->cover($this->box->width(), $this->box->height());
}
}

0 comments on commit ba1a78f

Please sign in to comment.