PHP Imagick resize with black background -
i writing php script using imagick extension. want script take image user uploads, , create 200x128 thumbnail out of it.
that's not thing. obviously, not images fit aspect ratio of 200x128. want script fill in gaps black background.
right now, image resizes, there no black background , size isn't correct. basically, image should 200x128. resized image go in center, , rest of contents filled black.
any ideas?
here's code:
function portfolio_image_search_resize($image) { // check if imagick loaded. if not, return false. if(!extension_loaded('imagick')) { return false; } // set dimensions of search result thumbnail $search_thumb_width = 200; $search_thumb_height = 128; // instantiate class. then, read image. $im = new imagick(); $im->readimage($image); // obtain image height , width $image_height = $im->getimageheight(); $image_width = $im->getimagewidth(); // determine if picture portrait or landscape $orientation = ($image_height > $image_width) ? 'portrait' : 'landscape'; // set compression , file type $im->setimagecompression(imagick::compression_jpeg); $im->setimagecompressionquality(100); $im->setresolution(72,72); $im->setimageformat('jpg'); switch($orientation) { case 'portrait': // since image must maintain aspect ratio, rest of image must appear black $im->setimagebackgroundcolor("black"); $im->scaleimage(0, $search_thumb_height); $filename = 'user_search_thumbnail.jpg'; // write image if($im->writeimage($filename) == true) { return true; } else { return false; } break; case 'landscape': // aspect ratio of image might not match search result thumbnail (1.5625) $im->setimagebackgroundcolor("black"); $calc_image_rsz_height = ($image_height / $image_width) * $search_thumb_width; if($calc_image_rsz_height > $search_thumb_height) { $im->scaleimage(0, $search_thumb_height); } else { $im->scaleimage($search_thumb_width, 0); } $filename = 'user_search_thumbnail.jpg'; if($im->writeimage($filename) == true) { return true; } else { return false; } break; } }
i know old found answer after long trying:
you need use thumbnailimage (http://php.net/manual/en/imagick.thumbnailimage.php)
with both $bestfit , $fill true so:
$image->thumbnailimage(200, 128,true,true);
Comments
Post a Comment