Segelparade / www / symfonyproject / src / Controller / DrawingController.php
DrawingController.php
Raw
<?php

namespace App\Controller;

use Imagick;
use ImagickPixel;
use ImagickDraw;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class DrawingController extends AbstractController
{
    public function index(Request $request): JsonResponse
    {
        // Decode JSON data from request
        $data = json_decode($request->getContent(), true);
        $coordinates = $data['coordinates'];
        // FS FEEDBACK DRAWING: so absolute paths
        $imagePath = '/var/www/html/symfonyproject/public/upload/' . $data['imagePath'];
        $cutImagePath = '/var/www/html/symfonyproject/public/processed/' . $data['cutImagePath'];

        // create Imagick pictute/layer from existing picture
        try {
            $image = new Imagick($imagePath);
        } catch (ImagickException $e) {
            // Handle the exception, log the error, or return an error response
            return new JsonResponse(['error' => 'Failed to load image: ' . $e->getMessage()], 500);
        }
        
        // Create a mask based on the drawn coordinates
        $mask = new Imagick();
        $mask->newImage($image->getImageWidth(), $image->getImageHeight(), new ImagickPixel('transparent'));

        // Draw a polygon in the mask based on the coordinates 
        $draw = new ImagickDraw();
        $draw->setFillColor('black');
        $draw->polygon($coordinates);
        $mask->drawImage($draw);
        // $mask->writeImage('/var/www/html/symfonyproject/public/upload/mask.png');

        // Apply the mask to the image
        $image->setImageFormat('png');
        $image->setImageMatte(1);
        $image->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0, Imagick::CHANNEL_ALPHA);
        
        // Save the masked image in selected path
        $image->writeImage($cutImagePath);

        // Clean up resources
        $image->clear();
        $mask->clear();
        $draw->clear();

        // Return a response to Javascript
        return new JsonResponse(['success' => true, 'output_path' => $cutImagePath]);
    }
}