Advertisement
Guest User

theme-thumbnails-resize.php

a guest
May 25th, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.62 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  *  Resizes an image and returns an array containing the resized URL, width, height and file type. Uses native Wordpress functionality.
  5.  *
  6.  *  Because Wordpress 3.5 has added the new 'WP_Image_Editor' class and depreciated some of the functions
  7.  *  we would normally rely on a separate function has been created for 3.5+.
  8.  *
  9.  *  Providing two separate functions means we can be backwards compatible and future proof. Hooray!
  10.  *
  11.  *  The first function (3.5+) supports GD Library and Imagemagick. Worpress will pick whichever is most appropriate.
  12.  *  The second function (3.4.2 and lower) only support GD Library.
  13.  *  If none of the supported libraries are available the function will bail and return the original image.
  14.  *
  15.  *  Both functions produce the exact same results when successful.
  16.  *  Images are saved to the Wordpress uploads directory, just like images uploaded through the Media Library.
  17.  *
  18.     *  Copyright 2013 Matthew Ruddy (http://easinglider.com)
  19.     *
  20.     *  This program is free software; you can redistribute it and/or modify
  21.     *  it under the terms of the GNU General Public License, version 2, as
  22.     *  published by the Free Software Foundation.
  23.     *
  24.     *  This program is distributed in the hope that it will be useful,
  25.     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  26.     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  27.     *  GNU General Public License for more details.
  28.     *
  29.     *  You should have received a copy of the GNU General Public License
  30.     *  along with this program; if not, write to the Free Software
  31.     *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  32.  *
  33.  *  @author Matthew Ruddy (http://easinglider.com)
  34.  *  @return array   An array containing the resized image URL, width, height and file type.
  35.  */
  36. if ( isset( $wp_version ) && version_compare( $wp_version, '3.5' ) >= 0 ) {
  37.     if (!function_exists('hb_resize')) {
  38.         function hb_resize($attach_id = null, $url = null, $width = NULL, $height = NULL, $crop = true, $retina = false) {
  39.  
  40.             if ($attach_id) {
  41.                 $url = wp_get_attachment_image_src($attach_id, 'full');
  42.                 $url = $url[0];
  43.             // this is not an attachment, let's use the image url
  44.             }
  45.  
  46.             global $wpdb;
  47.  
  48.             if (empty($url)) { return; }
  49.  
  50.     /* ----------------------------------------------------------------- */
  51.     /* MOD_START                                                         */
  52.     /* ----------------------------------------------------------------- */
  53.  
  54.             $file_path = ''; $dest_width = 0; $dest_height = 0;
  55.             if (!$width || !$width) {
  56.                 $file_path = get_attached_file($attach_id);
  57.                 list($origWidth, $origHeight) = getimagesize($file_path);
  58.                 $ratio = $origWidth / $origHeight;
  59.                 if (!$height) {
  60.                     $height = (int)round($width / $ratio);
  61.                     $dest_height = $height;
  62.                 }
  63.                 if (!$width) {
  64.                     $width = (int)round($height * $ratio);
  65.                     $dest_width = $width;
  66.                 }
  67.             }
  68.  
  69.     /* ----------------------------------------------------------------- */
  70.     /* MOD_END                                                           */
  71.     /* ----------------------------------------------------------------- */
  72.  
  73.             // Get default size from database
  74.             $width = ($width) ? $width : get_option('thumbnail_size_w');
  75.             $height = ($height) ? $height : get_option('thumbnail_size_h');
  76.  
  77.             // Allow for different retina sizes
  78.             $retina = $retina ? ($retina === true ? 2 : $retina) : 1;
  79.  
  80.             // Get the image file path
  81.             if (!$file_path) {
  82.                 $file_path = parse_url($url);
  83.                 $file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path['path'];
  84.             }
  85.  
  86.             // Check for Multisite
  87.             if (is_multisite()) {
  88.                 global $blog_id;
  89.                 $blog_details = get_blog_details($blog_id);
  90.                 $blog_path = $blog_details->path;
  91.  
  92.                 $pieces = explode('/', $blog_path);
  93.                 $good_path = implode('/', array_slice($pieces, 0, -2));
  94.  
  95.                 $file_path = str_replace($blog_details->path, $good_path . '/', $file_path);
  96.             }
  97.  
  98.             // Destination width and height variables
  99.             if (!$dest_width) { $dest_width = $width * $retina; }
  100.             if (!$dest_height) { $dest_height = $height * $retina; }
  101.  
  102.             // File name suffix (appended to original file name)
  103.             $suffix = "{$dest_width}x{$dest_height}";
  104.  
  105.             // Some additional info about the image
  106.             $info = pathinfo($file_path);
  107.             $dir = $info['dirname'];
  108.             $ext = $info['extension'];
  109.             $name = wp_basename($file_path, ".$ext");
  110.  
  111.             // Suffix applied to filename
  112.             $suffix = "{$dest_width}x{$dest_height}";
  113.  
  114.             // Get the destination file name
  115.             $dest_file_name = "{$dir}/{$name}-{$suffix}.{$ext}";
  116.  
  117.             if ($ext == "gif") {
  118.                 return array('url' => $url, 'width' => $width, 'height' => $height);
  119.             }
  120.  
  121.             if (!file_exists($dest_file_name)) {
  122.  
  123.                 /*
  124.                  *  Bail if this image isn't in the Media Library.
  125.                  *  We only want to resize Media Library images, so we can be sure they get deleted correctly when appropriate.
  126.                  */
  127.  
  128.     /* ----------------------------------------------------------------- */
  129.     /* MOD_START !important                                              */
  130.     /* ----------------------------------------------------------------- */
  131.  
  132.                 global $im_never_change_domains;
  133.                 if ($im_never_change_domains) {
  134.                     /* very stupid idea */
  135.                     $query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE guid='%s'", $url);
  136.                     $get_attachment = $wpdb->get_results($query);
  137.                     if (!$get_attachment) {
  138.                         return array('url' => $url, 'width' => $width, 'height' => $height);
  139.                     }
  140.                 }
  141.  
  142.     /* ----------------------------------------------------------------- */
  143.     /* MOD_END                                                           */
  144.     /* ----------------------------------------------------------------- */
  145.  
  146.                 // Load Wordpress Image Editor
  147.                 $editor = wp_get_image_editor($file_path);
  148.                 if (is_wp_error($editor)){
  149.                     return array('url' => $url, 'width' => $width, 'height' => $height);
  150.                 }
  151.  
  152.                 // Get the original image size
  153.                 $size = $editor->get_size();
  154.                 $orig_width = $size['width'];
  155.                 $orig_height = $size['height'];
  156.  
  157.                 $src_x = $src_y = 0;
  158.                 $src_w = $orig_width;
  159.                 $src_h = $orig_height;
  160.  
  161.                 if ($crop) {
  162.  
  163.                     $cmp_x = $orig_width / $dest_width;
  164.                     $cmp_y = $orig_height / $dest_height;
  165.  
  166.                     // Calculate x or y coordinate, and width or height of source
  167.                     if ($cmp_x > $cmp_y) {
  168.                         $src_w = round($orig_width / $cmp_x * $cmp_y);
  169.                         $src_x = round(($orig_width - ($orig_width / $cmp_x * $cmp_y)) / 2);
  170.                     }
  171.                     else if ($cmp_y > $cmp_x) {
  172.                         $src_h = round($orig_height / $cmp_y * $cmp_x);
  173.                         $src_y = round(($orig_height - ($orig_height / $cmp_y * $cmp_x)) / 2);
  174.                     }
  175.                 }
  176.  
  177.                 // Time to crop the image!
  178.                 $editor->crop($src_x, $src_y, $src_w, $src_h, $dest_width, $dest_height);
  179.  
  180.                 // Now let's save the image
  181.                 $saved = $editor->save($dest_file_name);
  182.  
  183.                 if (is_wp_error($saved)){
  184.                     return array('url' => $url, 'width' => $width, 'height' => $height);
  185.                 }
  186.  
  187.                 // Get resized image information
  188.                 $resized_url = str_replace(basename($url), basename($saved['path']), $url);
  189.                 $resized_width = $saved['width'];
  190.                 $resized_height = $saved['height'];
  191.                 $resized_type = $saved['mime-type'];
  192.  
  193.                 // Add the resized dimensions to original image metadata (so we can delete our resized images when the original image is delete from the Media Library)
  194.                 $metadata = wp_get_attachment_metadata($get_attachment[0]->ID);
  195.                 if (isset($metadata['image_meta'])) {
  196.                     $metadata['image_meta']['resized_images'][] = $resized_width .'x'. $resized_height;
  197.                     wp_update_attachment_metadata($get_attachment[0]->ID, $metadata);
  198.                 }
  199.  
  200.                 // Create the image array
  201.                 $image_array = array(
  202.                     'url' => $resized_url,
  203.                     'width' => $resized_width,
  204.                     'height' => $resized_height,
  205.                     'type' => $resized_type
  206.                 );
  207.  
  208.             }
  209.             else {
  210.                 $image_array = array(
  211.                     'url' => str_replace(basename($url), basename($dest_file_name), $url),
  212.                     'width' => $dest_width,
  213.                     'height' => $dest_height,
  214.                     'type' => $ext
  215.                 );
  216.             }
  217.  
  218.             // Return image array
  219.             return $image_array;
  220.  
  221.         }
  222.     }
  223. }
  224. else {
  225.     function hb_resize( $attach_id = null, $url = null, $width = NULL, $height = NULL, $crop = true, $retina = false ) {
  226.  
  227.         global $wpdb;
  228.  
  229.         if ( $attach_id ) {
  230.             $url = wp_get_attachment_image_src( $attach_id, 'full' );
  231.             $url = $url[0];
  232.         // this is not an attachment, let's use the image url
  233.         }
  234.  
  235.         if ( empty( $url ) )
  236.             return new WP_Error( 'no_image_url', __( 'No image URL has been entered.' , 'hbthemes'), $url );
  237.  
  238.         // Bail if GD Library doesn't exist
  239.         if ( !extension_loaded('gd') || !function_exists('gd_info') )
  240.             return array( 'url' => $url, 'width' => $width, 'height' => $height );
  241.  
  242.         // Get default size from database
  243.         $width = ( $width ) ? $width : get_option( 'thumbnail_size_w' );
  244.         $height = ( $height ) ? $height : get_option( 'thumbnail_size_h' );
  245.  
  246.         // Allow for different retina sizes
  247.         $retina = $retina ? ( $retina === true ? 2 : $retina ) : 1;
  248.  
  249.         // Destination width and height variables
  250.         $dest_width = $width * $retina;
  251.         $dest_height = $height * $retina;
  252.  
  253.         // Get image file path
  254.         $file_path = parse_url( $url );
  255.         $file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path['path'];
  256.  
  257.         // Check for Multisite
  258.         if ( is_multisite() ) {
  259.             global $blog_id;
  260.             $blog_details = get_blog_details( $blog_id );
  261.             $file_path = str_replace( $blog_details->path . 'files/', '/wp-content/blogs.dir/'. $blog_id .'/files/', $file_path );
  262.         }
  263.  
  264.         // Some additional info about the image
  265.         $info = pathinfo( $file_path );
  266.         $dir = $info['dirname'];
  267.         $ext = $info['extension'];
  268.         $name = wp_basename( $file_path, ".$ext" );
  269.  
  270.         // Suffix applied to filename
  271.         $suffix = "{$dest_width}x{$dest_height}";
  272.  
  273.         // Get the destination file name
  274.         $dest_file_name = "{$dir}/{$name}-{$suffix}.{$ext}";
  275.  
  276.         // No need to resize & create a new image if it already exists!
  277.         if ( !file_exists( $dest_file_name ) ) {
  278.  
  279.             /*
  280.              *  Bail if this image isn't in the Media Library either.
  281.              *  We only want to resize Media Library images, so we can be sure they get deleted correctly when appropriate.
  282.              */
  283.             $query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE guid='%s'", $url );
  284.             $get_attachment = $wpdb->get_results( $query );
  285.             if ( !$get_attachment )
  286.                 return array( 'url' => $url, 'width' => $width, 'height' => $height );
  287.  
  288.             $image = wp_get_image_editor( $file_path );
  289.  
  290.             if ( !is_resource( $image ) )
  291.                 return new WP_Error( 'error_loading_image_as_resource', $image, $file_path );
  292.  
  293.             // Get the current image dimensions and type
  294.             $size = @getimagesize( $file_path );
  295.             if ( !$size )
  296.                 return new WP_Error( 'file_path_getimagesize_failed', __( 'Failed to get $file_path information using "@getimagesize".', 'hbthemes'), $file_path );
  297.             list( $orig_width, $orig_height, $orig_type ) = $size;
  298.  
  299.             // Create new image
  300.             $new_image = wp_imagecreatetruecolor( $dest_width, $dest_height );
  301.  
  302.             // Do some proportional cropping if enabled
  303.             if ( $crop ) {
  304.  
  305.                 $src_x = $src_y = 0;
  306.                 $src_w = $orig_width;
  307.                 $src_h = $orig_height;
  308.  
  309.                 $cmp_x = $orig_width / $dest_width;
  310.                 $cmp_y = $orig_height / $dest_height;
  311.  
  312.                 // Calculate x or y coordinate, and width or height of source
  313.                 if ( $cmp_x > $cmp_y ) {
  314.                     $src_w = round( $orig_width / $cmp_x * $cmp_y );
  315.                     $src_x = round( ( $orig_width - ( $orig_width / $cmp_x * $cmp_y ) ) / 2 );
  316.                 }
  317.                 else if ( $cmp_y > $cmp_x ) {
  318.                     $src_h = round( $orig_height / $cmp_y * $cmp_x );
  319.                     $src_y = round( ( $orig_height - ( $orig_height / $cmp_y * $cmp_x ) ) / 2 );
  320.                 }
  321.  
  322.                 // Create the resampled image
  323.                 imagecopyresampled( $new_image, $image, 0, 0, $src_x, $src_y, $dest_width, $dest_height, $src_w, $src_h );
  324.  
  325.             }
  326.             else
  327.                 imagecopyresampled( $new_image, $image, 0, 0, 0, 0, $dest_width, $dest_height, $orig_width, $orig_height );
  328.  
  329.             // Convert from full colors to index colors, like original PNG.
  330.             if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )
  331.                 imagetruecolortopalette( $new_image, false, imagecolorstotal( $image ) );
  332.  
  333.             // Remove the original image from memory (no longer needed)
  334.             imagedestroy( $image );
  335.  
  336.             // Check the image is the correct file type
  337.             if ( IMAGETYPE_GIF == $orig_type ) {
  338.                 if ( !imagegif( $new_image, $dest_file_name ) )
  339.                     return new WP_Error( 'resize_path_invalid', __( 'Resize path invalid (GIF)' , 'hbthemes') );
  340.             }
  341.             elseif ( IMAGETYPE_PNG == $orig_type ) {
  342.                 if ( !imagepng( $new_image, $dest_file_name ) )
  343.                     return new WP_Error( 'resize_path_invalid', __( 'Resize path invalid (PNG).', 'hbthemes' ) );
  344.             }
  345.             else {
  346.  
  347.                 // All other formats are converted to jpg
  348.                 if ( 'jpg' != $ext && 'jpeg' != $ext )
  349.                     $dest_file_name = "{$dir}/{$name}-{$suffix}.jpg";
  350.                 if ( !imagejpeg( $new_image, $dest_file_name, apply_filters( 'resize_jpeg_quality', 90 ) ) )
  351.                     return new WP_Error( 'resize_path_invalid', __( 'Resize path invalid (JPG).', 'hbthemes' ) );
  352.  
  353.             }
  354.  
  355.             // Remove new image from memory (no longer needed as well)
  356.             imagedestroy( $new_image );
  357.  
  358.             // Set correct file permissions
  359.             $stat = stat( dirname( $dest_file_name ));
  360.             $perms = $stat['mode'] & 0000666;
  361.             @chmod( $dest_file_name, $perms );
  362.  
  363.             // Get some information about the resized image
  364.             $new_size = @getimagesize( $dest_file_name );
  365.             if ( !$new_size )
  366.                 return new WP_Error( 'resize_path_getimagesize_failed', __( 'Failed to get $dest_file_name (resized image) info via @getimagesize', 'hbthemes' ), $dest_file_name );
  367.             list( $resized_width, $resized_height, $resized_type ) = $new_size;
  368.  
  369.             // Get the new image URL
  370.             $resized_url = str_replace( basename( $url ), basename( $dest_file_name ), $url );
  371.  
  372.             // Add the resized dimensions to original image metadata (so we can delete our resized images when the original image is delete from the Media Library)
  373.             $metadata = wp_get_attachment_metadata( $get_attachment[0]->ID );
  374.             if ( isset( $metadata['image_meta'] ) ) {
  375.                 $metadata['image_meta']['resized_images'][] = $resized_width .'x'. $resized_height;
  376.                 wp_update_attachment_metadata( $get_attachment[0]->ID, $metadata );
  377.             }
  378.  
  379.             // Return array with resized image information
  380.             $image_array = array(
  381.                 'url' => $resized_url,
  382.                 'width' => $resized_width,
  383.                 'height' => $resized_height,
  384.                 'type' => $resized_type
  385.             );
  386.  
  387.         }
  388.         else {
  389.             $image_array = array(
  390.                 'url' => str_replace( basename( $url ), basename( $dest_file_name ), $url ),
  391.                 'width' => $dest_width,
  392.                 'height' => $dest_height,
  393.                 'type' => $ext
  394.             );
  395.         }
  396.  
  397.         return $image_array;
  398.  
  399.     }
  400. }
  401.  
  402. /**
  403.  *  Deletes the resized images when the original image is deleted from the Wordpress Media Library.
  404.  *
  405.  *  @author Matthew Ruddy
  406.  */
  407. add_action( 'delete_attachment', 'matthewruddy_delete_resized_images' );
  408. function matthewruddy_delete_resized_images( $post_id ) {
  409.  
  410.     // Get attachment image metadata
  411.     $metadata = wp_get_attachment_metadata( $post_id );
  412.     if ( !$metadata )
  413.         return;
  414.  
  415.     // Do some bailing if we cannot continue
  416.     if ( !isset( $metadata['file'] ) || !isset( $metadata['image_meta']['resized_images'] ) )
  417.         return;
  418.     $pathinfo = pathinfo( $metadata['file'] );
  419.     $resized_images = $metadata['image_meta']['resized_images'];
  420.  
  421.     // Get Wordpress uploads directory (and bail if it doesn't exist)
  422.     $wp_upload_dir = wp_upload_dir();
  423.     $upload_dir = $wp_upload_dir['basedir'];
  424.     if ( !is_dir( $upload_dir ) )
  425.         return;
  426.  
  427.     // Delete the resized images
  428.     foreach ( $resized_images as $dims ) {
  429.  
  430.         // Get the resized images filename
  431.         $file = $upload_dir .'/'. $pathinfo['dirname'] .'/'. $pathinfo['filename'] .'-'. $dims .'.'. $pathinfo['extension'];
  432.  
  433.         // Delete the resized image
  434.         @unlink( $file );
  435.  
  436.     }
  437.  
  438. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement