Skip to content

Instantly share code, notes, and snippets.

@jleehr
Created February 25, 2021 07:51
Show Gist options
  • Save jleehr/97571711155c835e649ee926d8977b81 to your computer and use it in GitHub Desktop.
Save jleehr/97571711155c835e649ee926d8977b81 to your computer and use it in GitHub Desktop.
Converter script to generate PDF files.
<?php
/**
* Image to PSD converter
*
* Converts an base64 encoded image (PNG) to PSD via ImageMagick.
*
* The receiving data must be an array with
* - id = Unique dataset id.
* - name = Image name.
* - images = Array with the image data.
* - base_path = The base path to write the images to; ending / is needed.
* - path = The path to write the images to; ending / is needed.
*
* Returns an array with the PSD file paths, keyed by the data['images'] array keys.
*/
$data = json_decode(file_get_contents('php://input'), true);
if(!is_array($data)) {
header('HTTP/1.0 500 Internal Server Error');
}
$id = $data['id'];
$name = $data['name'];
$images = $data['images'];
$base_path = $data['base_path'];
$path = $data['path'];
$psdFiles = array();
foreach ($images as $language => $base64String) {
$filename = $name . '_' . $id . '_' . $language . '.psd';
$psdPath = $path . 'psd/' . $filename;
// Get bas64 decoded data string
$base64 = explode(',', $base64String);
$blob = base64_decode($base64[1]);
$ifp = fopen($base_path . $psdPath, "wb");
// Write PSD
$image = new \Imagick(); //Create ImageMagick object
$image->readImageBlob($blob); //Fill image with data
$image->setImageUnits(\Imagick::RESOLUTION_PIXELSPERINCH); //Set resolution unit to ppi
$image->setImageResolution(300, 300); //Set resolution to 300dpi
$image->transformImageColorspace(\Imagick::COLORSPACE_CMYK); //Set colorspace to CMYK
$image->setImageFormat('psd'); //Set File ex. to PSD
$image->writeImageFile($ifp); //Write image file to disk.
// Clean image data
$image->clear();
$image->destroy();
// Close file handle
fclose($ifp);
$psdFiles[$language] = $psdPath;
}
// Send data back to requester
echo json_encode($psdFiles);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment