Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created June 28, 2018 14:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/96fa8bb3af0ee6fd821b3899e82d5fdb to your computer and use it in GitHub Desktop.
Save tommcfarlin/96fa8bb3af0ee6fd821b3899e82d5fdb to your computer and use it in GitHub Desktop.
[WordPress] Resizing Images Programmatically in WordPress
<?php
$filename = '/Users/tommcfarlin/Projects/acme/wp-content/uploads/2018/06/original-image.jpg';
if (!file_exists($filename)) {
return;
}
<?php
// Grab the editor for the filename of the image.
$filename = '/Users/tommcfarlin/Projects/acme/wp-content/uploads/2018/06/original-image.jpg';
if (!file_exists($filename)) {
return;
}
$editor = wp_get_image_editor( $filename, array() );
<?php
// Grab the editor for the file and the size of the original image.
$filename = '/Users/tommcfarlin/Projects/acme/wp-content/uploads/2018/06/original-image.jpg';
if (!file_exists($filename)) {
return;
}
$editor = wp_get_image_editor( $filename, array() );
if (is_wp_error($editor)) {
// handle the problem however you deem necessary.
}
<?php
// Grab the editor for the file and the size of the original image.
$filename = '/Users/tommcfarlin/Projects/acme/wp-content/uploads/2018/06/original-image.jpg';
if (!file_exists($filename)) {
return;
}
$editor = wp_get_image_editor( $filename, array() );
if (is_wp_error($editor)) {
// Handle the problem however you deem necessary.
}
// Get the dimensions for the size of the current image.
$dimensions = $editor->get_size();
$width = $dimensions['width'];
$height = $dimensions['height'];
// Calculate the new dimensions for the image.
$newWidth = 0.4 * $width;
$newHeight = 0.3 * $height;
// Resize the image.
$result = $editor->resize($newWidth, $newHeight, true);
<?php
// Grab the editor for the file and the size of the original image.
$filename = '/Users/tommcfarlin/Projects/acme/wp-content/uploads/2018/06/original-image.jpg';
if (!file_exists($filename)) {
return;
}
$editor = wp_get_image_editor( $filename, array() );
if (is_wp_error($editor)) {
// handle the problem however you deem necessary.
}
// Get the dimensions for the size of the current image.
$dimensions = $editor->get_size();
$width = $dimensions['width'];
$height = $dimensions['height'];
// Calculate the new dimensions for the image.
$newWidth = 0.4 * $width;
$newHeight = 0.3 * $height;
// Resize the image.
$result = $editor->resize($newWidth, $newHeight, true);
// If there's no problem, save it; otherwise, print the problem.
if (!is_wp_error($result)) {
$editor->save($editor->generate_filename());
} else {
// Handle the problem however you deem necessary.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment