Skip to content

Instantly share code, notes, and snippets.

@dimitryz
Last active December 23, 2015 07:28
Show Gist options
  • Save dimitryz/6600660 to your computer and use it in GitHub Desktop.
Save dimitryz/6600660 to your computer and use it in GitHub Desktop.
Quickly convert all images in the given and sub-directories to JPGs.
<?php
/**
* Converts all images in this directory and all subdirectories into JPGs.
*
* Example: php convert.php ~/Images
*
* Takes a directory as its only parameter and traverses it recursively looking for images. Whenever an image is found,
* this creates a copy of the image with the same name and the extension .jpg. Images with the extension .jpg will
* be overwritten.
*
* Author: Dimitry Zolotaryov (dimitry@webit.ca)
* Copyright: 2013 Dimitry Zolotaryov, MIT License
*/
if ( $argc < 2 ) die("Usage: convert.php [directory]");
$input_dir = $argv[1];
$full_dir = realpath( $input_dir );
if ( is_dir( $full_dir ) && is_readable( $full_dir ) ) {
print "Reading $full_dir for images\n";
convert_dir( $full_dir, array( 'echo' => true ) );
} else {
die( "$full_dir is not an accessible directory." );
}
/**
* Converts all .gif and .tif files in a directory to jpg.
*
*/
function convert_dir( $directory, $options = array() )
{
$directory = rtrim( $directory, DIRECTORY_SEPARATOR );
if ( !empty( $options['echo'] ) ) {
print "Reading directory $directory\n";
}
if ( $handle = opendir( $directory ) ) {
while ( false !== ( $entry = readdir( $handle ) ) ) {
$full_entry = $directory . DIRECTORY_SEPARATOR . $entry;
if ( is_dir( $full_entry ) && substr( $entry, 0, 1 ) != '.' ) {
convert_dir( $full_entry, $options );
} else if ( is_file( $full_entry ) ) {
convert_file( $full_entry, $options );
}
}
closedir( $handle );
} else {
if ( !empty( $options['echo'] ) ) {
print "Could not read $directory\n";
}
}
}
/**
* Converts the given .gif or .tif file to a .jpg of the same name.
*/
function convert_file( $file, $options = array() )
{
if ( !is_file( $file ) ) {
return;
}
if ( !getimagesize( $file ) ) {
if ( !empty( $options['echo'] ) ) {
print "Image $file is empty or not an image\n";
}
return;
}
$image = new Imagick( $file );
$file_info = pathinfo( $file );
$new_file = $file_info['dirname'] . DIRECTORY_SEPARATOR . $file_info['filename'] . '.jpg';
if ( file_exists( $new_file ) ) {
if ( !empty( $options['echo'] ) ) {
print "JPG $new_file already exists\n";
}
return;
}
$image->setFormat( 'jpg' );
if ( !empty( $options['echo'] ) ) {
print "Writing $new_file\n";
}
if ( !$image->writeImage( $new_file ) ) {
if ( !empty( $options['echo'] ) ) {
print "Could not write image $new_file\n";
}
} else {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment