Nick Duffell
Nick Duffell

Reputation: 340

Render fabric.js canvas json data to image file using ImageMagick

I know it's possible to get the image dataURL of the canvas client-side, or even use Node.js to render the canvas to an image file.

I am working with images of resolution ~9000x9000 and up though, and the above methods are slow / unreliable with images of this size.

Is it possible to read the JSON data I can get from fabric.js into PHP and render it server side with a graphics library like ImageMagick?

Cheers

Upvotes: 1

Views: 2034

Answers (1)

AZinkey
AZinkey

Reputation: 5319

Export your JSON data to a file or read directly then create a larger image using Imagick

   $print = new Imagick();
   $print->setResolution(300, 300);
   $background = #ff00ff;
   $print->newImage(9000, 9000, new ImagickPixel($background));

   $print->setImageFormat('png32');
   $print->setImageUnits(imagick::RESOLUTION_PIXELSPERCENTIMETER);

   // Re-Scaling each Image/Text for Larger Canvas/Image 
   foreach ($printData->json_data->objects as $i => $object) {

        addImage($object, $print, $printData);

  }


function addImage($object, $print, $printData) {

    $widthScale = ($printData->width / 300); fabric canvas width
    $heightScale = ($printData->height / 500); fabric canvas height
    $fileDir = dirname(__FILE__) . DS . 'media' . DS . 'original' . DS;
    $src = new Imagick($fileDir . basename($object->src));

    $size = $src->getImageGeometry();

    $resizeWidth = ($object->width * $object->scaleX) * $widthScale;
    $resizeHeight = ($object->height * $object->scaleY) * $heightScale;
    $src->resizeImage($resizeWidth, $resizeHeight, Imagick::FILTER_LANCZOS, 1);
    $sizeAfterResize = $src->getImageGeometry();

    $src->rotateImage(new ImagickPixel('none'), $object->angle);
    $sizeAfterRotate = $src->getImageGeometry();

        $left = $object->left * $widthScale;
        $top = $object->top * $heightScale; 

    $print->compositeImage($src, Imagick::COMPOSITE_DEFAULT, $left, $top);

}



try {
   // Saving High Quality Image in (300 dpi)
   $fileDir = dirname(__FILE__) . DS . 'media' . DS . 'prints';

   if (!file_exists($fileDir) || !is_dir($fileDir)) {
       if (!mkdir($fileDir))
           die("Could not create directory: {$fileDir}\n");
   }
   $saved = $print->writeimage($fileDir . DS . $id . '.png');
   header('Content-type: image/png');
   echo $print;
 } catch (Exception $e) {
      echo $e->getMessage();
 }

Upvotes: 1

Related Questions