iamcanadian1973
7/17/2015 - 12:58 AM

WordPress remote image resize

WordPress remote image resize

<?php

/**
 * WordPress - Resize and save remote images
 * 
 * @author Kyle Rumble
 * 
 * @param string $image
 * @param string $new_name
 * @param int $width
 * @param int $height
 * @param string $sub_directory
 * @param boolean $regenerate (default: FALSE)
 * @return string
 */
function _remote_img_resize_and_save( $image, $new_name, $width, $height, $sub_directory, $regenerate = FALSE ) {

	$upload_dir = wp_upload_dir();
	$basedir = $upload_dir['basedir'];
	$baseurl = $upload_dir['baseurl'];
	
	$file_info = pathinfo( $image );
	$file_name = $file_info['filename'];
	$extension = '.'. $file_info['extension'];

	$new_file_name = $new_name.'-'.$width.'x'.$height.$extension;
	$new_file_full_path = trailingslashit( $basedir ) . $sub_directory . '/' . $new_file_name;
	$new_file_full_url = trailingslashit( $baseurl ) . $sub_directory . '/' . $new_file_name;
	
	// To Do: set caching by filemtime
		
	// return resized image if exists	
	if ( file_exists( $new_file_full_path ) && !$regenerate ) {
		return $new_file_full_url;
	}
	
	$img = wp_get_image_editor( $image );
	if ( ! is_wp_error( $img ) ) {
		$img->resize( $width, $height, true );
		$details = $img->save( $new_file_full_path );
		return $new_file_full_url;
	}
	else {
		return $image;	
	}
}