Using ImageMagick to create an image from a PDF...efficiently

Posted by bigsweater on Stack Overflow See other posts from Stack Overflow or by bigsweater
Published on 2012-06-11T10:16:20Z Indexed on 2012/06/11 16:40 UTC
Read the original article Hit count: 222

Filed under:
|
|
|
|

I'm using ImageMagick to create a tiny JPG thumbnail image of an already-uploaded PDF. The code works fine. It's a WordPress widget, though this isn't necessarily WordPress specific.

I'm unfamiliar with ImageMagick, so I was hoping somebody could tell me if this looks terrible or isn't following some best practices of some sort, or if I'm risking crashing the server.

My questions, specifically, are:

  • Is that image cached, or does the server have to re-generate the image every time somebody views the page? If it isn't cached, what's the best way to make sure the server doesn't have to regenerate the thumbnail?
  • I tried to create a separate folder (/thumbs) for ImageMagick to put all the images in, instead of cluttering up the WP upload folders with images of PDFs. It kept throwing a permission error, despite 777 permissions on the folder in my testing environment. Why? Do the source/destination directories have to be the same?
  • Am I doing anything incorrectly/inefficiently here that needs to be improved?

The whole widget is on Pastebin: http://pastebin.com/WnSTEDm7

Relevant code:

<?php

if ( $url ) {       
    $pdf = $url;
    $info = pathinfo($pdf);
    $filename =  basename($pdf,'.'.$info['extension']);

    $uploads = wp_upload_dir();
    $file_path = str_replace( $uploads['baseurl'], $uploads['basedir'], $url );
    $dest_path = str_replace( '.pdf', '.jpg', $file_path );
    $dest_url = str_replace( '.pdf', '.jpg', $pdf );

    exec("convert \"{$file_path}[0]\" -colorspace RGB -geometry 60 $dest_path"); ?>
    <div class="entry">
        <div class="widgetImg">
            <p><a href="<?php echo $url; ?>" title="<?php echo $filename; ?>"><?php echo "<img src='".$dest_url."' alt='".$filename."' class='blueBorder' />"; ?></a></p>
        </div>

        <div class="widgetText">
            <?php echo wpautop( $desc ); ?>

            <p><a class="downloadLink" href="<?php echo $url; ?>" title="<?php echo $filename; ?>">Download</a></p>
        </div>
    </div>
    <?php }
?>

As you can see, the widget grabs whatever PDF is attached to the current page being viewed, creates an image of the first page of the PDF, stores it, then links to it in HTML.

Thanks for any and all help!

© Stack Overflow or respective owner

Related posts about php

Related posts about Wordpress