Skip to content

Instantly share code, notes, and snippets.

@ivanhoe011
Last active February 2, 2023 02:15
Show Gist options
  • Save ivanhoe011/4115733bd21ec988b1f6 to your computer and use it in GitHub Desktop.
Save ivanhoe011/4115733bd21ec988b1f6 to your computer and use it in GitHub Desktop.
Convert .ai, .psd, .jpg, .png, .gif into thumbnails
<?php
/**
* Convert
* http://stackoverflow.com/questions/12516842/convert-psd-and-ai-to-png-jpg-with-imagick
* @param string $dir Directory to save to.
* @param string $tmpName The name to name the file excluding the extension.
* @param string $fileType
* @param string $size Large or small.
*/
function thumbGenerator($dir,$tmpName,$fileType,$size){
$saveFileType = "png";
$imagePath = $dir.$tmpName.".".$fileType;
$image = new Imagick();
$image->readimage($imagePath);
if($fileType == "psd"){
$image->setIteratorIndex(0);
// Comment from StackOverflow:
// doesn't work for multilayer psd files
// but $image->setImageIndex(0) instead of $image->setIteratorIndex(0) does the work
}
$dimensions = $image->getImageGeometry();
$width = $dimensions['width'];
$height = $dimensions['height'];
if($size == "large"){
$maxWidth = 720;
$maxHeight =720;
}
if($size == "small"){
$maxWidth = 250;
$maxHeight =250;
}
if($height > $width){
//Portrait
if($height > $maxHeight)
$image->thumbnailImage(0, $maxHeight);
$dimensions = $image->getImageGeometry();
if($dimensions['width'] > $maxWidth){
$image->thumbnailImage($maxWidth, 0);
}
}elseif($height < $width){
//Landscape
$image->thumbnailImage($maxWidth, 0);
}else{
//square
$image->thumbnailImage($maxWidth, 0);
}
if($size == "large"){
$image->writeImage($dir . $tmpName."-lg.".$saveFileType);
}
if($size == "small"){
$image->writeImage($dir . $tmpName."-sm.".$saveFileType);;
}
}
/*
Other resources:
* http://phpflush.blogspot.com/2011/02/create-thumbnail-image-of-jpg-jpeg-png.html (not sure if it works?)
* http://www.multipole.org/discourse-server/viewtopic.php?f=1&t=18679
Using imagemagick:
convert 22495.psd -background white -flatten -density 300 -colors 512 -antialias -normalize \
-units PixelsPerInch -quality 100 -colorspace RGB -resize '3425x3425>' slozka/22495.jpg
* http://www.rubblewebs.co.uk/imagemagick/psd.php
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment