setImageFormat( "png" ); $im->getNumberImages(); // get number of pages (you can then loop through) $im->setResolution( 800, 800 ); // // If you're loading the PDF from a blob this is how you get the first page instead of the last page: // $im->readimageblob($blob); // $im->setiteratorindex(0); header( "Content-Type: image/png" ); echo $im; } /** * Crops an image based on the color of the top left pixel * Works with images that have blank space around the image * Tested on PNGs with white and transparent backgrounds * * @param $img Image resource or filename * @uses ImageMagick */ function web32_cropwhitespacefromimage( $img = null ) { // If there's no image if (!$img) { echo 'no file'; exit(); } // If the $img is a filename, convert it into an image resource if (is_string($img)) { $img = imagecreatefrompng( $img ); } // Get the width and height $width = imagesx($img); $height = imagesy($img); // Find the size of the borders $top = 0; $bottom = 0; $left = 0; $right = 0; $bgcolor = 0xFFFFFF; // Use this if you only want to crop out white space $bgcolor = imagecolorat( $img, $top, $left ); // This works with any color, including transparent backgrounds //top for(; $top < $height; ++$top) { for($x = 0; $x < $width; ++$x) { if(imagecolorat($img, $x, $top) != $bgcolor) { break 2; //out of the 'top' loop } } } //bottom for(; $bottom < $height; ++$bottom) { for($x = 0; $x < $width; ++$x) { if(imagecolorat($img, $x, $height - $bottom-1) != $bgcolor) { break 2; //out of the 'bottom' loop } } } //left for(; $left < $width; ++$left) { for($y = 0; $y < $height; ++$y) { if(imagecolorat($img, $left, $y) != $bgcolor) { break 2; //out of the 'left' loop } } } //right for(; $right < $width; ++$right) { for($y = 0; $y < $height; ++$y) { if(imagecolorat($img, $width - $right-1, $y) != $bgcolor) { break 2; //out of the 'right' loop } } } //copy the contents, excluding the border $newimg = imagecreate( $width-($left+$right), $height-($top+$bottom)); imagecopy($newimg, $img, 0, 0, $left, $top, imagesx($newimg), imagesy($newimg)); //finally, output the image header("Content-Type: image/png"); imagepng($newimg); } // end of function // web32_pdf_to_png('pdf.pdf'); web32_cropwhitespacefromimage('transparentbg.png'); // web32_cropwhitespacefromimage('chart2.png');