bigsweater
bigsweater

Reputation: 498

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

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:

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!

Upvotes: 0

Views: 2936

Answers (2)

Bonzo
Bonzo

Reputation: 5299

As you are saving as a jpg try adding -define to your code:

exec("convert -define jpeg:size=60x60 \"{$file_path}[0]\" -colorspace RGB -geometry 60 $dest_path"); ?> 

60x60 is the finished size of your image - all it does is read in enough data to create the image so speeding up the read process.

Resize keeping aspect then crop to 60x60

exec("convert -define jpeg:size=60x60 \"{$file_path}[0]\" -colorspace RGB -thumbnail 60x60 -gravity center -crop 60x60+0+0 +repage $dest_path"); ?> 

Upvotes: 1

bigsweater
bigsweater

Reputation: 498

So I think ImageMagick was re-generating the thumbnail on every page view. Pages with this widget would take an additional couple of seconds to load.

So, it now does a simple check to see if the thumbnail is already there:

if ( !file_exists( $dest_path ) ) {
    exec("convert \"{$file_path}[0]\" -colorspace RGB -geometry 60 $dest_path");
};

Pages that took ~5 seconds to load now take 2-3.

Regardless, I'm still interested to know if any PHP people think this could be done better.

Hope this code helps somebody out.

Upvotes: 0

Related Questions