/** * Title : Aqua Resizer * Description : Resizes WordPress images on the fly * Version : 1.1.5 * Author : Syamil MJ * Author URI : http://aquagraphite.com * License : WTFPL - http://sam.zoy.org/wtfpl/ * Documentation : https://github.com/sy4mil/Aqua-Resizer/ * * @param string $url - (required) must be uploaded using wp media uploader * @param int $width - (required) * @param int $height - (optional) * @param bool $crop - (optional) default to soft crop * @param bool $single - (optional) returns an array if false * @uses wp_upload_dir() * @uses image_resize_dimensions() * @uses image_resize() * * @return str|array */ function aq_resize($url, $width, $height = null, $crop = null, $single = true) { //validate inputs if (!$url or !$width) { return false; } //define upload path & dir $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; //check if $img_url is local if (strpos($url, $upload_url) === false) { return false; } //define path of image $rel_path = str_replace($upload_url, '', $url); $img_path = $upload_dir . $rel_path; //check if img path exists, and is an image indeed if (!file_exists($img_path) or !getimagesize($img_path)) { return false; } //get image info $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); //get image size after cropping $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; //use this to check if cropped image already exists, so we can return that instead $suffix = "{$dst_w}x{$dst_h}"; $dst_rel_path = str_replace('.' . $ext, '', $rel_path); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; if (!$dst_h) { //can't resize, so return original url $img_url = $url; $dst_w = $orig_w; $dst_h = $orig_h; } elseif (file_exists($destfilename) && getimagesize($destfilename)) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } else { $resized_img_path = image_resize($img_path, $width, $height, $crop); if (!is_wp_error($resized_img_path)) { $resized_rel_path = str_replace($upload_dir, '', $resized_img_path); $img_url = $upload_url . $resized_rel_path; } else { return false; } } //return the output if ($single) { //str return $image = $img_url; } else { //array return $image = array(0 => $img_url, 1 => $dst_w, 2 => $dst_h); } return $image; }
/** * This function is almost equal to the image_resize (native function of wordpress) */ function image_resize($file, $max_w, $max_h, $crop = false, $dest_path = null, $jpeg_quality = 90) { $image = wp_load_image($file); if (!is_resource($image)) { return new WP_Error('error_loading_image', $image); } $size = @getimagesize($file); if (!$size) { return new WP_Error('invalid_image', __('Could not read image size'), $file); } list($orig_w, $orig_h, $orig_type) = $size; $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop); if (!$dims) { $dims = array(0, 0, 0, 0, $orig_w, $orig_h, $orig_w, $orig_h); } list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $newimage = imagecreatetruecolor($dst_w, $dst_h); imagecopyresampled($newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); // convert from full colors to index colors, like original PNG. if (IMAGETYPE_PNG == $orig_type && !imageistruecolor($image)) { imagetruecolortopalette($newimage, false, imagecolorstotal($image)); } // we don't need the original in memory anymore imagedestroy($image); $info = pathinfo($dest_path); $dir = $info['dirname']; $ext = $info['extension']; $name = basename($dest_path, ".{$ext}"); $destfilename = "{$dir}/{$name}.{$ext}"; if (IMAGETYPE_GIF == $orig_type) { if (!imagegif($newimage, $destfilename)) { return new WP_Error('resize_path_invalid', __('Resize path invalid')); } } elseif (IMAGETYPE_PNG == $orig_type) { if (!imagepng($newimage, $destfilename)) { return new WP_Error('resize_path_invalid', __('Resize path invalid')); } } else { // all other formats are converted to jpg if (!imagejpeg($newimage, $destfilename, apply_filters('jpeg_quality', $jpeg_quality, 'image_resize'))) { return new WP_Error('resize_path_invalid', __('Resize path invalid')); } } imagedestroy($newimage); // Set correct file permissions $stat = stat(dirname($destfilename)); $perms = $stat['mode'] & 0666; //same permissions as parent folder, strip off the executable bits @chmod($destfilename, $perms); return $destfilename; }
function dynimg_generate_metadata($meta) { global $dynimg_image_sizes; foreach ($dynimg_image_sizes as $sizename => $size) { // figure out what size WP would make this: $newsize = image_resize_dimensions($meta['width'], $meta['height'], $size['width'], $size['height'], $size['crop']); if ($newsize) { $info = pathinfo($meta['file']); $ext = $info['extension']; $name = wp_basename($meta['file'], ".{$ext}"); $suffix = "{$newsize[4]}x{$newsize[5]}"; if ($size['crop']) { $suffix .= 'c'; } // build the fake meta entry for the size in question $resized = array('file' => "{$name}-{$suffix}.{$ext}", 'width' => $newsize[4], 'height' => $newsize[5]); $meta['sizes'][$sizename] = $resized; } } return $meta; }
/** * Resizes current image. * * At minimum, either a height or width must be provided. * If one of the two is set to null, the resize will * maintain aspect ratio according to the provided dimension. * * @access public * * @param int|null $max_w Image width. * @param int|null $max_h Image height. * @param boolean $crop * @return boolean|WP_Error */ public function resize($max_w, $max_h, $crop = false) { if ($this->size['width'] == $max_w && $this->size['height'] == $max_h) { return true; } $dims = image_resize_dimensions($this->size['width'], $this->size['height'], $max_w, $max_h, $crop); if (!$dims) { return new WP_Error('error_getting_dimensions', __('Could not calculate resized image dimensions')); } list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; if ($crop) { return $this->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h); } try { if ($this->mime_type === 'image/gif') { $this->image->scaleImage($dst_w, $dst_h); } else { $this->image->smartResize($dst_w, $dst_h, false); } } catch (Exception $e) { return new WP_Error('image_resize_error', $e->getMessage()); } return $this->update_size($dst_w, $dst_h); }
$Return = ''; if (!empty($Defaults[$Field])) { //compatibility $Value = explode('?', $Defaults[$Field]); $Value = $Value[0]; $imageWidth = $Config['_ImageSizeX'][$Field] == 'auto' ? '0' : $Config['_ImageSizeX'][$Field]; $imageHeight = $Config['_ImageSizeY'][$Field] == 'auto' ? '0' : $Config['_ImageSizeY'][$Field]; $iconWidth = $Config['_IconSizeX'][$Field] == 'auto' ? '0' : $Config['_IconSizeX'][$Field]; $iconHeight = $Config['_IconSizeY'][$Field] == 'auto' ? '0' : $Config['_IconSizeY'][$Field]; $uploadVars = wp_upload_dir(); $SourceFile = str_replace($uploadVars['url'], $uploadVars['path'], $Value); if (!file_exists($SourceFile)) { $Return .= 'Image does not exists.'; } $dim = getimagesize($SourceFile); $newDim = image_resize_dimensions($dim[0], $dim[1], $iconWidth, $iconHeight, true); $Sourcepath = pathinfo($SourceFile); $URLpath = pathinfo($Value); $iconURL = $URLpath['dirname'] . '/' . $URLpath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $URLpath['extension']; if (!file_exists($Sourcepath['dirname'] . '/' . $Sourcepath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $Sourcepath['extension'])) { $image = image_resize($SourceFile, $imageWidth, $imageHeight, true); $icon = image_resize($SourceFile, $iconWidth, $iconHeight, true); } $ClassName = ''; if (!empty($Config['_ImageClassName'][$Field])) { $ClassName = 'class="' . $Config['_ImageClassName'][$Field] . '" '; } if (!empty($Config['_IconURLOnly'][$Field])) { $Return .= $iconURL; } $Return .= '<img src="' . $iconURL . '" ' . $ClassName . image_hwstring($iconWidth, $iconHeight) . '>';
/** * Copy from wp-includes/media.php * Scale down an image to fit a particular size and save a new copy of the image. * * The PNG transparency will be preserved using the function, as well as the * image type. If the file going in is PNG, then the resized image is going to * be PNG. The only supported image types are PNG, GIF, and JPEG. * * Some functionality requires API to exist, so some PHP version may lose out * support. This is not the fault of WordPress (where functionality is * downgraded, not actual defects), but of your PHP version. * * @since 2.5.0 * * @param string $file Image file path. * @param int $max_w Maximum width to resize to. * @param int $max_h Maximum height to resize to. * @param bool $crop Optional. Whether to crop image or resize. * @param string $suffix Optional. File suffix. * @param string $dest_path Optional. New image file path. * @param int $jpeg_quality Optional, default is 90. Image quality percentage. * @return mixed WP_Error on failure. String with new destination path. */ function wpcf_image_resize($file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90) { $image = wp_load_image($file); if (!is_resource($image)) { return new WP_Error('error_loading_image', $image, $file); } $size = @getimagesize($file); if (!$size) { return new WP_Error('invalid_image', __('Could not read image size', 'wpcf'), $file); } list($orig_w, $orig_h, $orig_type) = $size; $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop); if (!$dims) { return new WP_Error('error_getting_dimensions', __('Could not calculate resized image dimensions', 'wpcf')); } list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $newimage = wp_imagecreatetruecolor($dst_w, $dst_h); imagecopyresampled($newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); // convert from full colors to index colors, like original PNG. if (IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor($image)) { imagetruecolortopalette($newimage, false, imagecolorstotal($image)); } // we don't need the original in memory anymore imagedestroy($image); // $suffix will be appended to the destination filename, just before the extension if (!$suffix) { $suffix = "{$dst_w}x{$dst_h}"; } $info = pathinfo($file); $dir = $info['dirname']; $ext = $info['extension']; $name = wpcf_basename($file, ".{$ext}"); // use fix here for windows if (!is_null($dest_path) and $_dest_path = realpath($dest_path)) { $dir = $_dest_path; } $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}"; if (IMAGETYPE_GIF == $orig_type) { if (!imagegif($newimage, $destfilename)) { return new WP_Error('resize_path_invalid', __('Resize path invalid', 'wpcf')); } } elseif (IMAGETYPE_PNG == $orig_type) { if (!imagepng($newimage, $destfilename)) { return new WP_Error('resize_path_invalid', __('Resize path invalid', 'wpcf')); } } else { // all other formats are converted to jpg if ('jpg' != $ext && 'jpeg' != $ext) { $destfilename = "{$dir}/{$name}-{$suffix}.jpg"; } if (!imagejpeg($newimage, $destfilename, apply_filters('jpeg_quality', $jpeg_quality, 'image_resize'))) { return new WP_Error('resize_path_invalid', __('Resize path invalid', 'wpcf')); } } imagedestroy($newimage); // Set correct file permissions $stat = stat(dirname($destfilename)); $perms = $stat['mode'] & 0666; //same permissions as parent folder, strip off the executable bits @chmod($destfilename, $perms); return $destfilename; }
/** * Retrieves the image's intermediate size (resized) path, width, and height. * * The $size parameter can be an array with the width and height respectively. * If the size matches the 'sizes' metadata array for width and height, then it * will be used. If there is no direct match, then the nearest image size larger * than the specified size will be used. If nothing is found, then the function * will break out and return false. * * The metadata 'sizes' is used for compatible sizes that can be used for the * parameter $size value. * * The url path will be given, when the $size parameter is a string. * * If you are passing an array for the $size, you should consider using * add_image_size() so that a cropped version is generated. It's much more * efficient than having to find the closest-sized image and then having the * browser scale down the image. * * @since 2.5.0 * * @param int $post_id Attachment ID. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array * of width and height values in pixels (in that order). * Default 'thumbnail'. * @return false|array $data { * Array of file relative path, width, and height on success. Additionally includes absolute * path and URL if registered size is passed to $size parameter. False on failure. * * @type string $file Image's path relative to uploads directory * @type int $width Width of image * @type int $height Height of image * @type string $path Optional. Image's absolute filesystem path. Only returned if registered * size is passed to `$size` parameter. * @type string $url Optional. Image's URL. Only returned if registered size is passed to `$size` * parameter. * } */ function image_get_intermediate_size($post_id, $size = 'thumbnail') { if (!is_array($imagedata = wp_get_attachment_metadata($post_id))) { return false; } // get the best one for a specified set of dimensions if (is_array($size) && !empty($imagedata['sizes'])) { $candidates = array(); foreach ($imagedata['sizes'] as $_size => $data) { // If there's an exact match to an existing image size, short circuit. if ($data['width'] == $size[0] && $data['height'] == $size[1]) { list($data['width'], $data['height']) = image_constrain_size_for_editor($data['width'], $data['height'], $size); /** This filter is documented in wp-includes/media.php */ return apply_filters('image_get_intermediate_size', $data, $post_id, $size); } // If it's not an exact match but it's at least the dimensions requested. if ($data['width'] >= $size[0] && $data['height'] >= $size[1]) { $candidates[$data['width'] * $data['height']] = $_size; } } if (!empty($candidates)) { // find for the smallest image not smaller than the desired size ksort($candidates); foreach ($candidates as $_size) { $data = $imagedata['sizes'][$_size]; // Skip images with unexpectedly divergent aspect ratios (crops) // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false); // If the size doesn't match within one pixel, then it is of a different aspect ratio, so we skip it, unless it's the thumbnail size if ('thumbnail' != $_size && (!$maybe_cropped || $maybe_cropped[4] != $data['width'] && $maybe_cropped[4] + 1 != $data['width'] || $maybe_cropped[5] != $data['height'] && $maybe_cropped[5] + 1 != $data['height'])) { continue; } // If we're still here, then we're going to use this size. list($data['width'], $data['height']) = image_constrain_size_for_editor($data['width'], $data['height'], $size); /** This filter is documented in wp-includes/media.php */ return apply_filters('image_get_intermediate_size', $data, $post_id, $size); } } } if (is_array($size) || empty($size) || empty($imagedata['sizes'][$size])) { return false; } $data = $imagedata['sizes'][$size]; // include the full filesystem path of the intermediate file if (empty($data['path']) && !empty($data['file'])) { $file_url = wp_get_attachment_url($post_id); $data['path'] = path_join(dirname($imagedata['file']), $data['file']); $data['url'] = path_join(dirname($file_url), $data['file']); } /** * Filter the output of image_get_intermediate_size() * * @since 4.4.0 * * @see image_get_intermediate_size() * * @param array $data Array of file relative path, width, and height on success. May also include * file absolute path and URL. * @param int $post_id The post_id of the image attachment * @param string|array $size Registered image size or flat array of initially-requested height and width * dimensions (in that order). */ return apply_filters('image_get_intermediate_size', $data, $post_id, $size); }
/** * Retrieves the image's intermediate size (resized) path, width, and height. * * The $size parameter can be an array with the width and height respectively. * If the size matches the 'sizes' metadata array for width and height, then it * will be used. If there is no direct match, then the nearest image size larger * than the specified size will be used. If nothing is found, then the function * will break out and return false. * * The metadata 'sizes' is used for compatible sizes that can be used for the * parameter $size value. * * The url path will be given, when the $size parameter is a string. * * If you are passing an array for the $size, you should consider using * add_image_size() so that a cropped version is generated. It's much more * efficient than having to find the closest-sized image and then having the * browser scale down the image. * * @since 2.5.0 * * @param int $post_id Attachment ID. * @param array|string $size Optional. Registered image size to retrieve or flat array of height * and width dimensions. Default 'thumbnail'. * @return false|array False on failure or array of file path, width, and height on success. */ function image_get_intermediate_size($post_id, $size = 'thumbnail') { if (!is_array($imagedata = wp_get_attachment_metadata($post_id))) { return false; } // get the best one for a specified set of dimensions if (is_array($size) && !empty($imagedata['sizes'])) { $areas = array(); foreach ($imagedata['sizes'] as $_size => $data) { // already cropped to width or height; so use this size if ($data['width'] == $size[0] && $data['height'] <= $size[1] || $data['height'] == $size[1] && $data['width'] <= $size[0]) { $file = $data['file']; list($width, $height) = image_constrain_size_for_editor($data['width'], $data['height'], $size); return compact('file', 'width', 'height'); } // add to lookup table: area => size $areas[$data['width'] * $data['height']] = $_size; } if (!$size || !empty($areas)) { // find for the smallest image not smaller than the desired size ksort($areas); foreach ($areas as $_size) { $data = $imagedata['sizes'][$_size]; if ($data['width'] >= $size[0] || $data['height'] >= $size[1]) { // Skip images with unexpectedly divergent aspect ratios (crops) // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false); // If the size doesn't match within one pixel, then it is of a different aspect ratio, so we skip it, unless it's the thumbnail size if ('thumbnail' != $_size && (!$maybe_cropped || $maybe_cropped[4] != $data['width'] && $maybe_cropped[4] + 1 != $data['width'] || $maybe_cropped[5] != $data['height'] && $maybe_cropped[5] + 1 != $data['height'])) { continue; } // If we're still here, then we're going to use this size $file = $data['file']; list($width, $height) = image_constrain_size_for_editor($data['width'], $data['height'], $size); return compact('file', 'width', 'height'); } } } } if (is_array($size) || empty($size) || empty($imagedata['sizes'][$size])) { return false; } $data = $imagedata['sizes'][$size]; // include the full filesystem path of the intermediate file if (empty($data['path']) && !empty($data['file'])) { $file_url = wp_get_attachment_url($post_id); $data['path'] = path_join(dirname($imagedata['file']), $data['file']); $data['url'] = path_join(dirname($file_url), $data['file']); } return $data; }
function aq_resize($url, $width, $height = null, $crop = null, $single = true) { if (of_get_option('image_resizing', '1') !== '1') { return $url; } //validate inputs if (!$url or !$width) { return false; } //set dimensions $aq_width = $width; $aq_height = $height; //define upload path & dir $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; //check if $img_url is local if (strpos($url, $upload_url) === false) { return false; } //define path of image $rel_path = str_replace($upload_url, '', $url); $img_path = $upload_dir . $rel_path; //check if img path exists, and is an image indeed if (!file_exists($img_path) or !getimagesize($img_path)) { return false; } //get image info $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); //get image size after cropping $dims = image_resize_dimensions($orig_w, $orig_h, $aq_width, $aq_height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; //use this to check if cropped image already exists, so we can return that instead $suffix = "{$dst_w}x{$dst_h}"; $dst_rel_path = str_replace('.' . $ext, '', $rel_path); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; if (!$dst_h) { //can't resize, so return original url $img_url = $url; $dst_w = $orig_w; $dst_h = $orig_h; } elseif (file_exists($destfilename) && getimagesize($destfilename)) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } else { $editor = wp_get_image_editor($img_path); if (is_wp_error($editor) || is_wp_error($editor->resize($aq_width, $aq_height, $crop))) { return false; } $editor->set_quality(100); // Added by WPExplorer $resized_file = $editor->save(); if (!is_wp_error($resized_file)) { $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']); $img_url = $upload_url . $resized_rel_path; } else { return false; } } //return the output if ($single) { //str return $image = $img_url; } else { //array return $image = array(0 => $img_url, 1 => $dst_w, 2 => $dst_h); } // RETINA Support - Added by WPExplorer ---------------------------------------------------------------> if (of_get_option('retina', '1') == '1') { $retina_w = $dst_w * 2; $retina_h = $dst_h * 2; //get image size after cropping $dims_x2 = image_resize_dimensions($orig_w, $orig_h, $retina_w, $retina_h, $crop); $dst_x2_w = $dims_x2[4]; $dst_x2_h = $dims_x2[5]; // If possible lets make the @2x image if ($dst_x2_h) { //@2x image url $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}@2x.{$ext}"; //check if retina image exists if (file_exists($destfilename) && getimagesize($destfilename)) { // already exists, do nothing } else { // doesnt exist, lets create it $editor = wp_get_image_editor($img_path); if (!is_wp_error($editor)) { $editor->resize($retina_w, $retina_h, $crop); $editor->set_quality(100); $filename = $editor->generate_filename($dst_w . 'x' . $dst_h . '@2x'); $editor = $editor->save($filename); } } } } // Return image ---------------------------------------------------------------> return $image; }
/** * Resizes current image. * * At minimum, either a height or width must be provided. * If one of the two is set to null, the resize will * maintain aspect ratio according to the provided dimension. * * @since 3.5.0 * @access public * * @param int|null $max_w Image width. * @param int|null $max_h Image height. * @param bool $crop * @return bool|WP_Error */ public function resize($max_w, $max_h, $crop = false) { if ($this->size['width'] == $max_w && $this->size['height'] == $max_h) { return true; } $dims = image_resize_dimensions($this->size['width'], $this->size['height'], $max_w, $max_h, $crop); if (!$dims) { return new WP_Error('error_getting_dimensions', __('Could not calculate resized image dimensions')); } list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; if ($crop) { return $this->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h); } try { /** * @TODO: Thumbnail is more efficient, given a newer version of Imagemagick. * $this->image->thumbnailImage( $dst_w, $dst_h ); */ $this->image->scaleImage($dst_w, $dst_h); } catch (Exception $e) { return new WP_Error('image_resize_error', $e->getMessage()); } return $this->update_size($dst_w, $dst_h); }
/** * Method for testing if an image WOULD be resized * Simulates the validation that occurs prior to actually beginning the resize * process that would negate the need for or prevent the image from being resized. * * We use image_make_intermediate_size() to create our images * This method recreates that. See media.php * * @since 0.1.5 * @uses wp_load_image() WP function * @uses image_resize_dimensions() WP function */ public static function simulate_image_make_intermediate_size($file, $width, $height, $crop = false) { // Begin image_make_intermediate_size($file, $width, $height, $crop=false) if ($width || $height) { // Begin image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) $image = wp_load_image($file); if (!is_resource($image)) { return FALSE; } //return new WP_Error( 'error_loading_image', $image, $file ); $size = @getimagesize($file); if (!$size) { return FALSE; } //return new WP_Error('invalid_image', __('Could not read image size'), $file); list($orig_w, $orig_h, $orig_type) = $size; $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); // $max_w, $max_h if (!$dims) { return FALSE; } //return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') ); list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; } imagedestroy($image); // Free up memory // Return value of image_make_intermediate_size() return array('file' => basename($file), 'width' => $dst_w, 'height' => $dst_h); }
/** * Use local random images for attachments * * @see WP_Import::process_attachment() */ public function process_attachment($post, $url) { $this->current_url = $url; if (!in_array($url, $this->attachments_original)) { // pick a random image if (is_array($this->the_images) && count($this->the_images)) { $image = $this->the_images[array_rand($this->the_images)]; $url = content_url(substr($image, strrpos($image, '/themes/'))); } else { return; } } // process at the parent // return parent::process_attachment($post, $url); /** * Code from WordPress Importer WP_Import::process_attachment() */ // if the URL is absolute, but does not contain address, then upload it assuming base_site_url if (preg_match('|^/[\\w\\W]+$|', $url)) { $url = rtrim($this->base_url, '/') . $url; } $upload = $this->fetch_remote_file($url, $post); if (is_wp_error($upload)) { return $upload; } if ($info = wp_check_filetype($upload['file'])) { $post['post_mime_type'] = $info['type']; } else { return new WP_Error('attachment_processing_error', __('Invalid file type', 'wordpress-importer')); } $post['guid'] = $upload['url']; // as per wp-admin/includes/upload.php $post_id = wp_insert_attachment($post, $upload['file']); $metadata = wp_generate_attachment_metadata($post_id, $upload['file']); wp_update_attachment_metadata($post_id, $metadata); // remap resized image URLs, works by stripping the extension and remapping the URL stub. if (preg_match('!^image/!', $info['type'])) { $url = $this->current_url; // old file - the local file from demo-data // new file - the new local file in uploads $parts = pathinfo($url); $parts_new = pathinfo($upload['url']); /** * Since images are dynamic, the aspect ratio might be different - so images that don't have a crop * will need changing the -1024xYYY.jpg part too */ $old_sizes = array(); foreach ($this->posts as $orig_post) { if ($orig_post['post_id'] == $post['import_id']) { foreach ($orig_post['postmeta'] as $meta) { if ($meta['key'] == '_wp_attachment_metadata') { $old_sizes = unserialize($meta['value']); $old_sizes = $old_sizes['sizes']; break; } } break; } } /* Large */ if (!empty($old_sizes['large'])) { $dims = image_resize_dimensions($metadata['width'], $metadata['height'], 1024, 1024); list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $old_ext = pathinfo($old_sizes['large']['file'], PATHINFO_EXTENSION); $name = $parts['filename'] . '-' . $old_sizes['large']['width'] . 'x' . $old_sizes['large']['height'] . '.' . $old_ext; $name_new = $parts_new['filename'] . "-{$dst_w}x{$dst_h}" . '.' . $parts['extension']; $this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new; } /* Medium */ if (!empty($old_sizes['medium'])) { $dims = image_resize_dimensions($metadata['width'], $metadata['height'], 300, 300); list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $old_ext = pathinfo($old_sizes['medium']['file'], PATHINFO_EXTENSION); $name = $parts['filename'] . '-' . $old_sizes['medium']['width'] . 'x' . $old_sizes['medium']['height'] . '.' . $old_ext; $name_new = $parts_new['filename'] . "-{$dst_w}x{$dst_h}" . '.' . $parts['extension']; $this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new; } /* Others - remap resized image URLs, works by stripping the extension and remapping the URL stub. */ $name = basename($parts['basename'], ".{$parts['extension']}"); // PATHINFO_FILENAME in PHP 5.2 $name_new = basename($parts_new['basename'], ".{$parts_new['extension']}"); $this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new; } return $post_id; }
function lrl_resize($url, $width, $height = null, $crop = null, $single = true) { //Validate inputs if (!$url or !$width) { return false; } //Define upload path & dir $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; //Check if $img_url is local if (strpos($url, $upload_url) === false) { return false; } //Define path of image $rel_path = str_replace($upload_url, '', $url); $img_path = $upload_dir . $rel_path; //Check if img path exists, and is an image indeed if (!file_exists($img_path) or !getimagesize($img_path)) { return false; } //Get image info $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); //Get image size after cropping $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; //Use this to check if cropped image already exists, so we can return that instead $suffix = "{$dst_w}x{$dst_h}"; $dst_rel_path = str_replace('.' . $ext, '', $rel_path); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; if (!$dst_h) { //Can't resize, so return original url $img_url = $url; $dst_w = $orig_w; $dst_h = $orig_h; } elseif (file_exists($destfilename) && getimagesize($destfilename)) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } else { // Note: This pre-3.5 fallback check will edited out in subsequent version if (function_exists('wp_get_image_editor')) { $editor = wp_get_image_editor($img_path); if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop))) { return false; } $resized_file = $editor->save(); if (!is_wp_error($resized_file)) { $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']); $img_url = $upload_url . $resized_rel_path; } else { return false; } } else { $resized_img_path = image_resize($img_path, $width, $height, $crop); // Fallback foo if (!is_wp_error($resized_img_path)) { $resized_rel_path = str_replace($upload_dir, '', $resized_img_path); $img_url = $upload_url . $resized_rel_path; } else { return false; } } } //Return the output if ($single) { //str return $image = $img_url; } else { //Array return $image = array(0 => $img_url, 1 => $dst_w, 2 => $dst_h); } return $image; }
/** * Use WP_Image_Editor to create a resized image and return the URL for that image * * @param array $orig_size * @param array $dest_size * @return string */ private function resize_image($orig_size, $dest_size, $dest_file_name) { // load image $image = wp_get_image_editor($this->path); // editor will return an error if the path is invalid if (is_wp_error($image)) { if (is_admin()) { echo '<div id="message" class="error">'; echo "<p><strong>ERROR</strong> " . $image->get_error_message() . " Check <a href='http://codex.wordpress.org/Changing_File_Permissions' target='_blank'>file permissions</a></p>"; echo "<button class='toggle'>Show Details</button>"; echo "<div class='message' style='display: none;'><br />Slide ID: {$this->id}<pre>"; var_dump($image); echo "</pre></div>"; echo "</div>"; } return $this->url; } $dims = image_resize_dimensions($orig_size['width'], $orig_size['height'], $dest_size['width'], $dest_size['height'], true); if ($dims) { list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $image->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h); } $saved = $image->save($dest_file_name); if (is_wp_error($saved)) { return $this->url; } // Record the new size so that the file is correctly removed when the media file is deleted. $backup_sizes = get_post_meta($this->id, '_wp_attachment_backup_sizes', true); if (!is_array($backup_sizes)) { $backup_sizes = array(); } $backup_sizes["resized-{$dest_size['width']}x{$dest_size['height']}"] = $saved; update_post_meta($this->id, '_wp_attachment_backup_sizes', $backup_sizes); $url = str_replace(basename($this->url), basename($saved['path']), $this->url); return $url; }
/** Uses WP's Image Editor Class to resize and filter images * Inspired by: https://github.com/sy4mil/Aqua-Resizer/blob/master/aq_resizer.php * * @param $url string the local image URL to manipulate * @param $params array the options to perform on the image. Keys and values supported: * 'width' int pixels * 'height' int pixels * 'opacity' int 0-100 * 'color' string hex-color #000000-#ffffff * 'grayscale' bool * 'crop' bool * 'negate' bool * @param $single boolean, if false then an array of data will be returned * @return string|array */ public static function thumb($url, $params = array(), $single = true) { extract($params); //validate inputs if (!$url) { return false; } //define upload path & dir $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; $theme_url = get_template_directory_uri(); $theme_dir = get_template_directory(); // find the path of the image. Perform 2 checks: // #1 check if the image is in the uploads folder if (strpos($url, $upload_url) !== false) { $rel_path = str_replace($upload_url, '', $url); $img_path = $upload_dir . $rel_path; // #2 check if the image is in the current theme folder } else { if (strpos($url, $theme_url) !== false) { $rel_path = str_replace($theme_url, '', $url); $img_path = $theme_dir . $rel_path; } } // Fail if we can't find the image in our WP local directory if (empty($img_path)) { return $url; } //check if img path exists, and is an image indeed if (!@file_exists($img_path) or !getimagesize($img_path)) { return $url; } // This is the filename $basename = basename($img_path); //get image info $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); // support percentage dimensions. compute percentage based on // the original dimensions if (isset($width)) { if (stripos($width, '%') !== false) { $width = (int) ((double) str_replace('%', '', $width) / 100 * $orig_w); } } if (isset($height)) { if (stripos($height, '%') !== false) { $height = (int) ((double) str_replace('%', '', $height) / 100 * $orig_h); } } // The only purpose of this is to detemine the final width and height // without performing any actual image manipulation, which will be used // to check whether a resize was previously done. if (isset($width)) { //get image size after cropping $dims = image_resize_dimensions($orig_w, $orig_h, $width, isset($height) ? $height : null, isset($crop) ? $crop : false); $dst_w = $dims[4]; $dst_h = $dims[5]; } // create the suffix for the saved file // we can use this to check whether we need to create a new file or just use an existing one. $suffix = (string) filemtime($img_path) . (isset($width) ? str_pad((string) $width, 5, '0', STR_PAD_LEFT) : '00000') . (isset($height) ? str_pad((string) $height, 5, '0', STR_PAD_LEFT) : '00000') . (isset($opacity) ? str_pad((string) $opacity, 3, '0', STR_PAD_LEFT) : '100') . (isset($color) ? str_pad(preg_replace('#^\\##', '', $color), 8, '0', STR_PAD_LEFT) : '00000000') . (isset($grayscale) ? $grayscale ? '1' : '0' : '0') . (isset($crop) ? $crop ? '1' : '0' : '0') . (isset($negate) ? $negate ? '1' : '0' : '0'); $suffix = self::base_convert_arbitrary($suffix, 10, 36); // use this to check if cropped image already exists, so we can return that instead $dst_rel_path = str_replace('.' . $ext, '', basename($img_path)); // If opacity is set, change the image type to png if (isset($opacity)) { $ext = 'png'; } // Create the upload subdirectory, this is where // we store all our generated images if (defined('BFITHUMB_UPLOAD_DIR')) { $upload_dir .= "/" . BFITHUMB_UPLOAD_DIR; $upload_url .= "/" . BFITHUMB_UPLOAD_DIR; } else { $upload_dir .= "/bfi_thumb"; $upload_url .= "/bfi_thumb"; } if (!is_dir($upload_dir)) { wp_mkdir_p($upload_dir); } // desination paths and urls $destfilename = "{$upload_dir}/{$dst_rel_path}-{$suffix}.{$ext}"; $img_url = "{$upload_url}/{$dst_rel_path}-{$suffix}.{$ext}"; // if file exists, just return it if (@file_exists($destfilename) && getimagesize($destfilename)) { } else { // perform resizing and other filters $editor = wp_get_image_editor($img_path); if (is_wp_error($editor)) { return false; } /* * Perform image manipulations */ if (isset($width) && $width || isset($height) && $height) { if (is_wp_error($editor->resize(isset($width) ? $width : null, isset($height) ? $height : null, isset($crop) ? $crop : false))) { return false; } } if (isset($negate)) { if ($negate) { if (is_wp_error($editor->negate())) { return false; } } } if (isset($opacity)) { if (is_wp_error($editor->opacity($opacity))) { return false; } } if (isset($grayscale)) { if ($grayscale) { if (is_wp_error($editor->grayscale())) { return false; } } } if (isset($color)) { if (is_wp_error($editor->colorize($color))) { return false; } } // save our new image $mime_type = isset($opacity) ? 'image/png' : null; $resized_file = $editor->save($destfilename, $mime_type); } //return the output if ($single) { $image = $img_url; } else { //array return $image = array(0 => $img_url, 1 => isset($dst_w) ? $dst_w : $orig_w, 2 => isset($dst_h) ? $dst_h : $orig_h); } return $image; }
/** * Resizes current image. * * At minimum, either a height or width must be provided. * If one of the two is set to null, the resize will * maintain aspect ratio according to the provided dimension. * * @since 3.5.0 * @access public * * @param int|null $max_w Image width. * @param int|null $max_h Image height. * @param bool $crop * @return bool|WP_Error */ public function resize($max_w, $max_h, $crop = false) { if ($this->size['width'] == $max_w && $this->size['height'] == $max_h) { return true; } $dims = image_resize_dimensions($this->size['width'], $this->size['height'], $max_w, $max_h, $crop); if (!$dims) { return new WP_Error('error_getting_dimensions', __('Could not calculate resized image dimensions')); } list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; if ($crop) { return $this->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h); } // Execute the resize $thumb_result = $this->thumbnail_image($dst_w, $dst_h); if (is_wp_error($thumb_result)) { return $thumb_result; } return $this->update_size($dst_w, $dst_h); }
/** * Scale down an image to fit a particular size and save a new copy of the image. * * The PNG transparency will be preserved using the function, as well as the * image type. If the file going in is PNG, then the resized image is going to * be PNG. The only supported image types are PNG, GIF, and JPEG. * * Some functionality requires API to exist, so some PHP version may lose out * support. This is not the fault of WordPress (where functionality is * downgraded, not actual defects), but of your PHP version. * * @since 2.5.0 * * @param string $file Image file path. * @param int $max_w Maximum width to resize to. * @param int $max_h Maximum height to resize to. * @param bool $crop Optional. Whether to crop image or resize. * @param string $suffix Optional. File Suffix. * @param string $dest_path Optional. New image file path. * @param int $jpeg_quality Optional, default is 90. Image quality percentage. * @return mixed WP_Error on failure. String with new destination path. Array of dimensions from {@link image_resize_dimensions()} */ function image_resize($file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90) { $image = wp_load_image($file); if (!is_resource($image)) { return new WP_Error('error_loading_image', $image); } list($orig_w, $orig_h, $orig_type) = getimagesize($file); $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop); if (!$dims) { return $dims; } list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $newimage = imagecreatetruecolor($dst_w, $dst_h); // preserve PNG transparency if (IMAGETYPE_PNG == $orig_type && function_exists('imagealphablending') && function_exists('imagesavealpha')) { imagealphablending($newimage, false); imagesavealpha($newimage, true); } imagecopyresampled($newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); // we don't need the original in memory anymore imagedestroy($image); // $suffix will be appended to the destination filename, just before the extension if (!$suffix) { $suffix = "{$dst_w}x{$dst_h}"; } $info = pathinfo($file); $dir = $info['dirname']; $ext = $info['extension']; $name = basename($file, ".{$ext}"); if (!is_null($dest_path) and $_dest_path = realpath($dest_path)) { $dir = $_dest_path; } $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}"; if ($orig_type == IMAGETYPE_GIF) { if (!imagegif($newimage, $destfilename)) { return new WP_Error('resize_path_invalid', __('Resize path invalid')); } } elseif ($orig_type == IMAGETYPE_PNG) { if (!imagepng($newimage, $destfilename)) { return new WP_Error('resize_path_invalid', __('Resize path invalid')); } } else { // all other formats are converted to jpg $destfilename = "{$dir}/{$name}-{$suffix}.jpg"; if (!imagejpeg($newimage, $destfilename, apply_filters('jpeg_quality', $jpeg_quality, 'image_resize'))) { return new WP_Error('resize_path_invalid', __('Resize path invalid')); } } imagedestroy($newimage); // Set correct file permissions $stat = stat(dirname($destfilename)); $perms = $stat['mode'] & 0666; //same permissions as parent folder, strip off the executable bits @chmod($destfilename, $perms); return $destfilename; }
/** * Run image resizing function * * @since 1.0.0 */ public function process($args) { // Args must be an array if (!is_array($args)) { print_r('Fatal Error: Image resize args are not an array, you must update your template files.'); return false; } // Default args $defaults = array('image' => null, 'width' => '9999', 'height' => '9999', 'crop' => 'center-center', 'retina' => false, 'return' => 'array'); // Parse args $args = wp_parse_args($args, $defaults); // Extract args extract($args); // If URL isn't defined return if (!$image) { return; } // Sanitize inputs $width = intval($width); $height = intval($height); // Set width and height to '9999' if empty $width = $width ? $width : '9999'; $height = $height ? $height : '9999'; // Set crop to center-center if empty $crop = $crop ? $crop : 'center-center'; // Sanitize crop and add crop suffix $crop_suffix = ''; $crop = $height >= '9999' ? false : $crop; // Define upload path & dir $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; // Define path of image $rel_path = str_replace($upload_url, '', $image); $img_path = $upload_dir . $rel_path; // Add crop_suffix if $crop isn't false or empty and image resizing is enabled if ($crop && wpex_get_mod('image_resizing', true)) { if (is_array($crop)) { $crop_suffix = array_combine($crop, $crop); $crop_suffix = implode('-', $crop_suffix); } elseif ('center-center' != $crop) { $crop_suffix = $crop; $crop = explode('-', $crop); } } // If image width and height are both 9999 and size is empty return full image if ('9999' == $width && '9999' == $height) { // Return for retina images if ($retina) { return; } // Set main image to the full URL $img_url = $image; // Get width and height $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); } else { // Set resize dimensions $resize_width = $width; $resize_height = $height; // If $img_url isn't local return full image if (strpos($image, $upload_url) === false) { $img_url = $image; } else { // Check if img path exists, and is an image indeed if not return full img if (!file_exists($img_path) or !getimagesize($img_path)) { $img_url = $image; } else { // Get image info $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); // Get image size after cropping $dims = image_resize_dimensions($orig_w, $orig_h, $resize_width, $resize_height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; // Can't resize, so return original url if (!$dims) { // Set values equal to original image $img_url = $image; $dst_w = $orig_w; $dst_h = $orig_h; // Return false for retina if ($retina) { return false; } } else { // Define image saving destination $dst_rel_path = str_replace('.' . $ext, '', $rel_path); // Suffix $suffix = $dst_w . 'x' . $dst_h; // Sanitize suffix $suffix = $crop_suffix ? $crop_suffix . '-' . $suffix : $suffix; // Check original image destination $destfilename = $upload_dir . $dst_rel_path . '-' . $suffix . '.' . $ext; // Set dimensions for retina images if ($retina) { // Check if we should actually create a retina version if ($dims && file_exists($destfilename) && getimagesize($destfilename)) { // Return if the destination width or height aren't at least 2x as big if ($orig_w < $dst_w * 2 || $orig_h < $dst_h * 2) { return false; } // Set retina version to @2x the output of the default cropped image $dims = image_resize_dimensions($orig_w, $orig_h, $dst_w * 2, $dst_h * 2, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; // Return if retina version can't be created if (!$dims) { return false; } // Set correct resize dims for retina images $resize_width = $resize_width * 2; $resize_height = $resize_height * 2; // Tweak suffix $suffix .= '@2x'; $suffix = $crop_suffix ? $crop_suffix . '-' . $suffix : $suffix; } else { return false; } } // The full destination filename for the cropped image $destfilename = $upload_dir . $dst_rel_path . '-' . $suffix . '.' . $ext; // Check if cache exists if (file_exists($destfilename) && getimagesize($destfilename)) { // Set image url $img_url = $upload_url . $dst_rel_path . '-' . $suffix . '.' . $ext; } else { $editor = wp_get_image_editor($img_path); // Return full image if there is an error if (is_wp_error($editor) || is_wp_error($editor->resize($resize_width, $resize_height, $crop))) { $img_url = $image; } else { // Get resized file $filename = $editor->generate_filename($suffix); $editor = $editor->save($filename); // Return the resized image URL if (!is_wp_error($editor)) { $path = str_replace($upload_dir, '', $editor['path']); $img_url = $upload_url . $path; } else { $img_url = $image; } } } // End cache check } // End $dims check } // End file exists check } // End local image check } // End image dims check // Validate url $img_url = !empty($img_url) ? $img_url : $image; // Validate width if (!empty($dst_w)) { $dst_w = $dst_w; } elseif (isset($orig_w)) { $dst_w = $orig_w; } else { $dst_w = ''; } // Validate height if (!empty($dst_h)) { $dst_h = $dst_h; } elseif (isset($orig_h)) { $dst_h = $orig_h; } else { $dst_h = ''; } // Return Image data if ('array' == $return) { return array('url' => $img_url, 'width' => $dst_w, 'height' => $dst_h); } else { return $img_url; } }
/** * Run, forest. */ public function process($url, $width = null, $height = null, $crop = null, $single = true, $upscale = false) { try { // Validate inputs. if (!$url) { throw new Aq_Exception('$url parameter is required'); } if (!$width) { throw new Aq_Exception('$width parameter is required'); } if (!$height) { throw new Aq_Exception('$height parameter is required'); } // Caipt'n, ready to hook. if (true === $upscale) { add_filter('image_resize_dimensions', array($this, 'aq_upscale'), 10, 6); } // Define upload path & dir. $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; $http_prefix = "http://"; $https_prefix = "https://"; $relative_prefix = "//"; // The protocol-relative URL /* if the $url scheme differs from $upload_url scheme, make them match if the schemes differe, images don't show up. */ if (!strncmp($url, $https_prefix, strlen($https_prefix))) { //if url begins with https:// make $upload_url begin with https:// as well $upload_url = str_replace($http_prefix, $https_prefix, $upload_url); } elseif (!strncmp($url, $http_prefix, strlen($http_prefix))) { //if url begins with http:// make $upload_url begin with http:// as well $upload_url = str_replace($https_prefix, $http_prefix, $upload_url); } elseif (!strncmp($url, $relative_prefix, strlen($relative_prefix))) { //if url begins with // make $upload_url begin with // as well $upload_url = str_replace(array(0 => "{$http_prefix}", 1 => "{$https_prefix}"), $relative_prefix, $upload_url); } // Check if $img_url is local. if (false === strpos($url, $upload_url)) { $upload_info = $this->jv_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; } // Define path of image. $rel_path = str_replace($upload_url, '', $url); $img_path = $upload_dir . $rel_path; // Check if img path exists, and is an image indeed. if (!file_exists($img_path) or !getimagesize($img_path)) { throw new Aq_Exception('Image file does not exist (or is not an image) : ' . $img_path); } // Get image info. $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); // Get image size after cropping. $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; // Return the original image only if it exactly fits the needed measures. if (!$dims && (null === $height && $orig_w == $width xor null === $width && $orig_h == $height xor $height == $orig_h && $width == $orig_w)) { $img_url = $url; $dst_w = $orig_w; $dst_h = $orig_h; } else { // Use this to check if cropped image already exists, so we can return that instead. $suffix = "{$dst_w}x{$dst_h}"; $dst_rel_path = str_replace('.' . $ext, '', $rel_path); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; if (!$dims || true == $crop && false == $upscale && ($dst_w < $width || $dst_h < $height)) { // Can't resize, so return false saying that the action to do could not be processed as planned. throw new Aq_Exception('Unable to resize image because image_resize_dimensions() failed'); } elseif (file_exists($destfilename) && getimagesize($destfilename)) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } else { $editor = wp_get_image_editor($img_path); if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop))) { throw new Aq_Exception('Unable to get WP_Image_Editor: ' . $editor->get_error_message() . ' (is GD or ImageMagick installed?)'); } $resized_file = $editor->save(); if (!is_wp_error($resized_file)) { $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']); $img_url = $upload_url . $resized_rel_path; } else { throw new Aq_Exception('Unable to save resized image file: ' . $editor->get_error_message()); } } } // Okay, leave the ship. if (true === $upscale) { remove_filter('image_resize_dimensions', array($this, 'aq_upscale')); } // Return the output. if ($single) { // str return. $image = $img_url; } else { // array return. $image = array(0 => $img_url, 1 => $dst_w, 2 => $dst_h); } return $image; } catch (Aq_Exception $ex) { error_log('Aq_Resize.process() error: ' . $ex->getMessage()); if ($this->throwOnError) { // Bubble up exception. throw $ex; } else { // Return false, so that this patch is backwards-compatible. return false; } } }
/** * Removes generated custom image sizes. * @param int $post_id * @return void */ public function removeCustomImageSizes($post_id) { $file_dir = get_attached_file($post_id); if (empty($file_dir)) { return; } $imageSizes = $this->getCustomImageSizes(); if (!$imageSizes) { return; } $file_dir_info = pathinfo($file_dir); $file_base_dir = isset($file_dir_info['dirname']) ? $file_dir_info['dirname'] : ''; $file_name = isset($file_dir_info['filename']) ? $file_dir_info['filename'] : ''; $file_ext = isset($file_dir_info['extension']) ? $file_dir_info['extension'] : ''; foreach ($imageSizes as $size) { $crop = $size['crop']; $width = $size['width']; $height = $size['height']; if (false == $crop) { // get image size after cropping list($orig_w, $orig_h) = getimagesize($file_dir); $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); $width = $dims[4]; $height = $dims[5]; } $file = $file_base_dir . '/' . $file_name . '-' . $width . 'x' . $height . '.' . $file_ext; if (!file_exists($file)) { continue; } if (unlink($file)) { // files remove } else { // files not remove } } }
/** * Use WP_Image_Editor to create a resized image and return the URL for that image * * @param array $orig_size * @param array $dest_size * @return string */ private function resize_image($orig_size, $dest_size, $dest_file_name) { // load image $image = wp_get_image_editor($this->path); // editor will return an error if the path is invalid if (is_wp_error($image)) { $capability = apply_filters('hw_metaslider_capability', 'edit_others_posts'); if (is_admin() && current_user_can($capability)) { echo '<div id="message" class="error">'; echo "<p><strong>ERROR</strong> Slide ID: {$this->id} - <i>" . $image->get_error_message() . "</i></p>"; echo "</div>"; } return $this->url; } $crop_position = $this->get_crop_position(); $dims = image_resize_dimensions($orig_size['width'], $orig_size['height'], $dest_size['width'], $dest_size['height'], $crop_position); if ($dims) { list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $image->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h); } $saved = $image->save($dest_file_name); if (is_wp_error($saved)) { return $this->url; } // Record the new size so that the file is correctly removed when the media file is deleted. $backup_sizes = get_post_meta($this->id, '_wp_attachment_backup_sizes', true); if (!is_array($backup_sizes)) { $backup_sizes = array(); } $backup_sizes["resized-{$dest_size['width']}x{$dest_size['height']}"] = $saved; update_post_meta($this->id, '_wp_attachment_backup_sizes', $backup_sizes); $url = str_replace(basename($this->url), basename($saved['path']), $this->url); return $url; }
/** * Title : Aqua Resizer * Description : Resizes WordPress images on the fly * Version : 1.1.7 * Author : Syamil MJ * Author URI : http://aquagraphite.com * License : WTFPL - http://sam.zoy.org/wtfpl/ * Documentation : https://github.com/sy4mil/Aqua-Resizer/ * * @param string $url - (required) must be uploaded using wp media uploader * @param int $width - (required) * @param int $height - (optional) * @param bool $crop - (optional) default to soft crop * @param bool $single - (optional) returns an array if false * @uses wp_upload_dir() * @uses image_resize_dimensions() | image_resize() * @uses wp_get_image_editor() * * @return str|array */ function aq_resize( $url, $width = null, $height = null, $crop = null, $single = true, $upscale = false) { //validate inputs if(!$url || (!$width && !$height)) return false; // caipt'n, ready to hook if($upscale === true) add_filter('image_resize_dimensions', 'aq_upscale', 10, 6); //define upload path & dir $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; //check if $img_url is local if(strpos( $url, $upload_url ) === false) return false; //define path of image $rel_path = str_replace( $upload_url, '', $url); $img_path = $upload_dir . $rel_path; //check if img path exists, and is an image indeed if( !file_exists($img_path) OR !getimagesize($img_path) ) return false; //get image info $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w,$orig_h) = getimagesize($img_path); //get image size after cropping $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; // return the original image only if it exactly fits the needed measures if(!$dims && ((($height === null && $orig_w == $width) xor ($width === null && $orig_h == $height)) xor ($height == $orig_h && $width == $orig_w))) { $img_url = $url; $dst_w = $orig_w; $dst_h = $orig_h; } else { //use this to check if cropped image already exists, so we can return that instead $suffix = "{$dst_w}x{$dst_h}"; $dst_rel_path = str_replace( '.'.$ext, '', $rel_path); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; if(!$dims || ($crop == true && $upscale == false && ($dst_w < $width || $dst_h < $height))) { //can't resize, so return false saying that the action to do could not be processed as planned. return $url; } //else check if cache exists elseif(file_exists($destfilename) && getimagesize($destfilename)) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } //else, we resize the image and return the new resized image url else { // Note: This pre-3.5 fallback check will edited out in subsequent version if(function_exists('wp_get_image_editor')) { $editor = wp_get_image_editor($img_path); if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) return false; $resized_file = $editor->save(); if(!is_wp_error($resized_file)) { $resized_rel_path = str_replace( $upload_dir, '', $resized_file['path']); $img_url = $upload_url . $resized_rel_path; } else { return false; } } else { $resized_img_path = image_resize( $img_path, $width, $height, $crop ); // Fallback foo if(!is_wp_error($resized_img_path)) { $resized_rel_path = str_replace( $upload_dir, '', $resized_img_path); $img_url = $upload_url . $resized_rel_path; } else { return false; } } } } // okay, leave the ship if($upscale === true) remove_filter('image_resize_dimensions', 'aq_upscale'); //return the output if($single) { //str return $image = $img_url; } else { //array return $image = array ( 0 => $img_url, 1 => $dst_w, 2 => $dst_h ); } return $image; }
/** * Filter post thumbnail image retrieval, passing images through Photon * * @param string|bool $image * @param int $attachment_id * @param string|array $size * @uses is_admin, apply_filters, wp_get_attachment_url, self::validate_image_url, this::image_sizes, jetpack_photon_url * @filter image_downsize * @return string|bool */ public function filter_image_downsize($image, $attachment_id, $size) { // Don't foul up the admin side of things, and provide plugins a way of preventing Photon from being applied to images. if (is_admin() || apply_filters('jetpack_photon_override_image_downsize', false, compact('image', 'attachment_id', 'size'))) { return $image; } // Get the image URL and proceed with Photon-ification if successful $image_url = wp_get_attachment_url($attachment_id); // Set this to true later when we know we have size meta. $has_size_meta = false; if ($image_url) { // Check if image URL should be used with Photon if (!self::validate_image_url($image_url)) { return $image; } $intermediate = true; // For the fourth array item returned by the image_downsize filter. // If an image is requested with a size known to WordPress, use that size's settings with Photon if ((is_string($size) || is_int($size)) && array_key_exists($size, self::image_sizes())) { $image_args = self::image_sizes(); $image_args = $image_args[$size]; $photon_args = array(); $image_meta = image_get_intermediate_size($attachment_id, $size); // 'full' is a special case: We need consistent data regardless of the requested size. if ('full' == $size) { $image_meta = wp_get_attachment_metadata($attachment_id); $intermediate = false; } elseif (!$image_meta) { // If we still don't have any image meta at this point, it's probably from a custom thumbnail size // for an image that was uploaded before the custom image was added to the theme. Try to determine the size manually. $image_meta = wp_get_attachment_metadata($attachment_id); if (isset($image_meta['width'], $image_meta['height'])) { $image_resized = image_resize_dimensions($image_meta['width'], $image_meta['height'], $image_args['width'], $image_args['height'], $image_args['crop']); if ($image_resized) { // This could be false when the requested image size is larger than the full-size image. $image_meta['width'] = $image_resized[6]; $image_meta['height'] = $image_resized[7]; } } } if (isset($image_meta['width'], $image_meta['height'])) { $image_args['width'] = $image_meta['width']; $image_args['height'] = $image_meta['height']; list($image_args['width'], $image_args['height']) = image_constrain_size_for_editor($image_args['width'], $image_args['height'], $size, 'display'); $has_size_meta = true; } // Expose determined arguments to a filter before passing to Photon $transform = $image_args['crop'] ? 'resize' : 'fit'; // Check specified image dimensions and account for possible zero values; photon fails to resize if a dimension is zero. if (0 == $image_args['width'] || 0 == $image_args['height']) { if (0 == $image_args['width'] && 0 < $image_args['height']) { $photon_args['h'] = $image_args['height']; } elseif (0 == $image_args['height'] && 0 < $image_args['width']) { $photon_args['w'] = $image_args['width']; } } else { if ('resize' === $transform && ($image_meta = wp_get_attachment_metadata($attachment_id))) { if (isset($image_meta['width'], $image_meta['height'])) { // Lets make sure that we don't upscale images since wp never upscales them as well $smaller_width = $image_meta['width'] < $image_args['width'] ? $image_meta['width'] : $image_args['width']; $smaller_height = $image_meta['height'] < $image_args['height'] ? $image_meta['height'] : $image_args['height']; $photon_args[$transform] = $smaller_width . ',' . $smaller_height; } } else { $photon_args[$transform] = $image_args['width'] . ',' . $image_args['height']; } } /** * Filter the Photon Arguments added to an image when going through Photon, when that image size is a string. * Image size will be a string (e.g. "full", "medium") when it is known to WordPress. * * @module photon * * @since 2.0.0 * * @param array $photon_args Array of Photon arguments. * @param array $args { * Array of image details. * * @type $image_args Array of Image arguments (width, height, crop). * @type $image_url Image URL. * @type $attachment_id Attachment ID of the image. * @type $size Image size. Can be a string (name of the image size, e.g. full) or an integer. * @type $transform Value can be resize or fit. * @see https://developer.wordpress.com/docs/photon/api * } */ $photon_args = apply_filters('jetpack_photon_image_downsize_string', $photon_args, compact('image_args', 'image_url', 'attachment_id', 'size', 'transform')); // Generate Photon URL $image = array(jetpack_photon_url($image_url, $photon_args), $has_size_meta ? $image_args['width'] : false, $has_size_meta ? $image_args['height'] : false, $intermediate); } elseif (is_array($size)) { // Pull width and height values from the provided array, if possible $width = isset($size[0]) ? (int) $size[0] : false; $height = isset($size[1]) ? (int) $size[1] : false; // Don't bother if necessary parameters aren't passed. if (!$width || !$height) { return $image; } $image_meta = wp_get_attachment_metadata($attachment_id); if (isset($image_meta['width'], $image_meta['height'])) { $image_resized = image_resize_dimensions($image_meta['width'], $image_meta['height'], $width, $height); if ($image_resized) { // This could be false when the requested image size is larger than the full-size image. $width = $image_resized[6]; $height = $image_resized[7]; } else { $width = $image_meta['width']; $height = $image_meta['height']; } $has_size_meta = true; } list($width, $height) = image_constrain_size_for_editor($width, $height, $size); // Expose arguments to a filter before passing to Photon $photon_args = array('fit' => $width . ',' . $height); /** * Filter the Photon Arguments added to an image when going through Photon, * when the image size is an array of height and width values. * * @module photon * * @since 2.0.0 * * @param array $photon_args Array of Photon arguments. * @param array $args { * Array of image details. * * @type $width Image width. * @type height Image height. * @type $image_url Image URL. * @type $attachment_id Attachment ID of the image. * } */ $photon_args = apply_filters('jetpack_photon_image_downsize_array', $photon_args, compact('width', 'height', 'image_url', 'attachment_id')); // Generate Photon URL $image = array(jetpack_photon_url($image_url, $photon_args), $has_size_meta ? $width : false, $has_size_meta ? $height : false, $intermediate); } } return $image; }
protected function _resize($max_w, $max_h, $crop = false) { $dims = image_resize_dimensions($this->size['width'], $this->size['height'], $max_w, $max_h, $crop); if (!$dims) { return new WP_Error('error_getting_dimensions', __('Could not calculate resized image dimensions'), $this->file); } list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $resized = wp_imagecreatetruecolor($dst_w, $dst_h); imagecopyresampled($resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); if (is_resource($resized)) { $this->update_size($dst_w, $dst_h); return $resized; } return new WP_Error('image_resize_error', __('Image resize failed.'), $this->file); }
function file_processValue($Value, $Type, $Field, $Config, $EID) { if (!empty($Value)) { //dump($Value); //dump($Type); //dump($Field); //dump($Config); //die; switch ($Type) { case 'image': $Value = strtok($Value, '?'); $imageWidth = $Config['_ImageSizeX'][$Field] == 'auto' ? '100' : $Config['_ImageSizeX'][$Field]; $imageHeight = $Config['_ImageSizeY'][$Field] == 'auto' ? '100' : $Config['_ImageSizeY'][$Field]; $iconWidth = $Config['_IconSizeX'][$Field] == 'auto' ? '100' : $Config['_IconSizeX'][$Field]; $iconHeight = $Config['_IconSizeY'][$Field] == 'auto' ? '100' : $Config['_IconSizeY'][$Field]; $uploadVars = wp_upload_dir(); $SourceFile = str_replace($uploadVars['baseurl'], $uploadVars['basedir'], $Value); if (!file_exists($SourceFile)) { return 'Image does not exists.'; } $dim = getimagesize($SourceFile); $newDim = image_resize_dimensions($dim[0], $dim[1], $iconWidth, $iconHeight, true); if (!empty($newDim)) { $Sourcepath = pathinfo($SourceFile); $URLpath = pathinfo($Value); $iconURL = $URLpath['dirname'] . '/' . $URLpath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $URLpath['extension']; if (!file_exists($Sourcepath['dirname'] . '/' . $Sourcepath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $Sourcepath['extension'])) { $image = image_resize($SourceFile, $imageWidth, $imageHeight, true); $icon = image_resize($SourceFile, $iconWidth, $iconHeight, true); } } else { $iconURL = $Value; $iconWidth = $dim[0]; $iconHeight = $dim[1]; } $ClassName = ''; if (!empty($Config['_ImageClassName'][$Field])) { $ClassName = 'class="' . $Config['_ImageClassName'][$Field] . '" '; } if (!empty($Config['_IconURLOnly'][$Field])) { return $iconURL; } return '<img src="' . $iconURL . '" ' . $ClassName . image_hwstring($iconWidth, $iconHeight) . '>'; break; case 'mp3': $File = explode('?', $Value); $UniID = uniqid($EID . '_'); //$ReturnData = '<span id="'.$UniID.'">'.$File[1].'</span>'; $ReturnData = '<audio id="' . $UniID . '" src="' . $File[0] . '">unavailable</audio>'; $_SESSION['dataform']['OutScripts'] .= "\n\t\t\t\t\tAudioPlayer.embed(\"" . $UniID . "\", {\n\t\t\t\t\t"; if (!empty($Config['_PlayerCFG']['Autoplay'][$Field])) { $_SESSION['dataform']['OutScripts'] .= " autostart: 'yes', "; } if (!empty($Config['_PlayerCFG']['Animation'][$Field])) { $_SESSION['dataform']['OutScripts'] .= " animation: 'yes', "; } $_SESSION['dataform']['OutScripts'] .= "\n transparentpagebg: 'yes',\n\t\t\t\t\t\tsoundFile: \"" . $File[0] . "\",\n\t\t\t\t\t\ttitles: \"" . $File[1] . "\"\n\t\t\t\t\t});\n\n\t\t\t\t"; $_SESSION['dataform']['OutScripts'] .= "\n jQuery(document).ready(function(\$) {\n AudioPlayer.setup(\"" . WP_PLUGIN_URL . "/db-toolkit/data_form/fieldtypes/file/player.swf\", {\n width: '100%',\n initialvolume: 100,\n transparentpagebg: \"yes\",\n left: \"000000\",\n lefticon: \"FFFFFF\"\n });\n });"; return $ReturnData; break; case 'file': case 'multi': if (empty($Config['_fileReturnValue'][$Field])) { $Config['_fileReturnValue'][$Field] = 'iconlink'; } $pathInfo = pathinfo($Value); $s3Enabled = false; $prime = $Field; if (!empty($Config['_CloneField'][$Field]['Master'])) { $prime = $Config['_CloneField'][$Field]['Master']; } if (!empty($Config['_enableS3'][$prime]) && !empty($Config['_AWSAccessKey'][$prime]) && !empty($Config['_AWSSecretKey'][$prime])) { include_once DB_TOOLKIT . 'data_form/fieldtypes/file/s3.php'; $s3 = new S3($Config['_AWSAccessKey'][$prime], $Config['_AWSSecretKey'][$prime]); $s3Enabled = true; } switch ($Config['_fileReturnValue'][$Field]) { case 'iconlink': if (empty($Value)) { return 'no file uploaded'; } if (!empty($Config['_enableS3'][$prime]) && !empty($Config['_AWSAccessKey'][$prime]) && !empty($Config['_AWSSecretKey'][$prime])) { $File = 'http://' . $Config['_AWSBucket'][$prime] . '.s3.amazonaws.com/' . $Value; } else { $File = $Value; } $Dets = pathinfo($File); $ext = strtolower($Dets['extension']); if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/file/icons/' . $ext . '.gif')) { $Icon = '<img src="' . WP_PLUGIN_URL . '/db-toolkit/data_form/fieldtypes/file/icons/' . $ext . '.gif" align="absmiddle" /> '; } else { $Icon = '<img src="' . WP_PLUGIN_URL . '/db-toolkit/data_form/fieldtypes/file/icons/file.gif" align="absmiddle" /> '; } return '<a href="' . $File . '">' . $Icon . ' ' . basename($File) . '</a>'; break; case 'filesize': if (!empty($s3Enabled)) { $object = $s3->getObjectInfo($Config['_AWSBucket'][$prime], $Value); return file_return_bytes($object['size']); } else { $uploadDir = wp_upload_dir(); $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value); return file_return_bytes(filesize($file)); } break; case 'filesizeraw': if (!empty($s3Enabled)) { $object = $s3->getObjectInfo($Config['_AWSBucket'][$prime], $Value); return $object['size']; } else { $uploadDir = wp_upload_dir(); $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value); return filesize($file); } break; case 'filename': if (!empty($s3Enabled)) { return basename($Value); } else { return $pathInfo['basename']; } break; case 'filepath': return $Value; break; case 'ext': return $pathInfo['extension']; break; case 'mimetype': $uploadDir = wp_upload_dir(); $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value); $type = wp_check_filetype($file); return $type['type']; break; } break; } return; } }
/** * @param $post_id (int) The post to a sell media item post type * @param $term_id (int) The term id for a term from the price-group taxonomy * @param $size_not_available (bool) If true returns and array of unavailable sizes * * @return Array of downloadable sizes or single size if $term_id is present */ public function get_downloadable_size($post_id = null, $attachment_id = null, $term_id = null, $size_not_available = false) { $null = null; $download_sizes = array(); /** * Loop over price groups checking for children, * compare the width and height assigned to a price group * with the width and height of the current image. Remove * sizes that are not downloadable. */ $size_groups = sell_media_get_price_groups($post_id, 'price-group'); if (!empty($size_groups)) { $image = $this->get_original_image_size($attachment_id); foreach ($size_groups as $size) { /** * Check for children only */ if ($size->parent > 0) { /** * Retrieve the height and width for our price group */ $pg_width = sell_media_get_term_meta($size->term_id, 'width', true); $pg_height = sell_media_get_term_meta($size->term_id, 'height', true); /** * Build our array to be returned, the downloadable width and height * are calculated later and added to this array */ $download_sizes[$size->term_id] = array('name' => $size->name); /** * Calculate dimensions and coordinates for a resized image that fits * within a specified width and height. If $crop is true, the largest * matching central portion of the image will be cropped out and resized * to the required size. * * Note we need to pass in $null due to what image_resize_dimensions() returns */ list($null, $null, $null, $null, $download_sizes[$size->term_id]['width'], $download_sizes[$size->term_id]['height']) = image_resize_dimensions($image['original']['width'], $image['original']['height'], $pg_width, $pg_height, $crop = false); /** * If no width/height can be determined we remove it from our array of * available download sizes. */ if (empty($download_sizes[$size->term_id]['width'])) { $unavailable_size[$size->term_id] = array('name' => $download_sizes[$size->term_id]['name'], 'height' => $pg_height, 'width' => $pg_width); unset($download_sizes[$size->term_id]); } /** * Check for portraits and if the available download size is larger than * the original we remove it. */ $terms = wp_get_post_terms($post_id, 'price-group'); $heights[] = ''; if (!empty($terms)) { foreach ($terms as $term) { if ($term->parent != 0) { $height = sell_media_get_term_meta($term->term_id, 'height', true); $heights[] = $height; } } } $smallest_height = min($heights); /** * Compare the original image size with our array of images sizes from * Price Groups array, removing items that are not available. */ if ($image['original']['height'] >= $image['original']['width'] && isset($download_sizes[$size->term_id]) && $download_sizes[$size->term_id]['height'] <= $smallest_height) { $unavailable_size[$size->term_id] = array('name' => $download_sizes[$size->term_id]['name'], 'price' => $download_sizes[$size->term_id]['price'], 'height' => $pg_height, 'width' => $pg_width); unset($download_sizes[$price->term_id]); } } } } // Returns an array of available and unavailable sizes if ($size_not_available) { $sizes = array('available' => $download_sizes, 'unavailable' => empty($unavailable_size) ? null : $unavailable_size); } elseif (empty($term_id)) { $sizes = $download_sizes; } else { // Since we no longer check if the image sold is available in the download sizes // we allow the buyer to download the original image if the size they purchased // is larger than the original image i.e., they can purchase a size they can never // download. // // Hence if they paid for the original, OR they paid for a larger image than // available they get the original image. $sizes = empty($download_sizes[$term_id]) ? 'original' : $download_sizes[$term_id]; } return $sizes; }
function sf_aq_resize($url, $width, $height = null, $crop = null, $single = true) { $debug_mode = false; if (isset($_GET['sf_debug'])) { $debug_mode = $_GET['sf_debug']; } if ($debug_mode) { echo 'IMAGE DEBUG' . "\n"; } if (!function_exists('wp_get_image_editor')) { if ($debug_mode) { echo 'wp_get_image_editor function does not exist' . "\n"; } } //validate inputs if (!$width or !$url) { return false; } if ($url == "default") { $url = get_template_directory_uri() . "/images/default-thumb.png"; $image = array(0 => $url, 1 => '1600', 2 => '1600'); return $image; } //define upload path & dir $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; $http_prefix = "http://"; $https_prefix = "https://"; /* if the $url scheme differs from $upload_url scheme, make them match if the schemes differe, images don't show up. */ if (!strncmp($url, $https_prefix, strlen($https_prefix))) { //if url begins with https:// make $upload_url begin with https:// as well $upload_url = str_replace($http_prefix, $https_prefix, $upload_url); } elseif (!strncmp($url, $http_prefix, strlen($http_prefix))) { //if url begins with http:// make $upload_url begin with http:// as well $upload_url = str_replace($https_prefix, $http_prefix, $upload_url); } //check if $img_url is local if (!sf_wpml_activated()) { if (strpos($url, home_url()) === false) { if ($debug_mode) { echo 'not local' . "\n"; } $image = array(0 => $url, 1 => $width, 2 => $height); return $image; } } //define path of image $rel_path = str_replace($upload_url, '', $url); $img_path = $upload_dir . $rel_path; //check if img path exists, and is an image indeed if (!sf_wpml_activated()) { if (!file_exists($img_path) or !getimagesize($img_path)) { if ($debug_mode) { echo 'file does not exist' . "\n"; } $image = array(0 => $url, 1 => $width, 2 => $height); return $image; } } //get image info $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); //get image size after cropping $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; //use this to check if cropped image already exists, so we can return that instead $suffix = "{$dst_w}x{$dst_h}"; $dst_rel_path = str_replace('.' . $ext, '', $rel_path); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; //if orig size is smaller if ($width >= $orig_w) { if (!$dst_h) { //can't resize, so return original url if ($debug_mode) { "can't resize, so return original url"; } $img_url = $url; $dst_w = $orig_w; $dst_h = $orig_h; } else { //else check if cache exists if (file_exists($destfilename) && getimagesize($destfilename)) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } else { if (function_exists('wp_get_image_editor')) { $editor = wp_get_image_editor($img_path); if ($debug_mode) { var_dump($editor); } if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop))) { $image = array(0 => $url, 1 => $width, 2 => $height); return $image; } $resized_file = $editor->save(); if (!is_wp_error($resized_file)) { $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']); $img_url = $upload_url . $resized_rel_path; } else { return false; } } } } } elseif (file_exists($destfilename) && getimagesize($destfilename)) { if ($debug_mode) { "cache exists"; } $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } else { if (function_exists('wp_get_image_editor')) { $editor = wp_get_image_editor($img_path); if ($debug_mode) { var_dump($editor); } if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop))) { $image = array(0 => $url, 1 => $width, 2 => $height); return $image; } $resized_file = $editor->save(); if (!is_wp_error($resized_file)) { $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']); $img_url = $upload_url . $resized_rel_path; } else { return false; } } } //return the output if ($single) { //str return $image = $img_url; } else { //array return $image = array(0 => $img_url, 1 => $dst_w, 2 => $dst_h); } return $image; }
/** * Returns an array of properties of a resulting clone image if and when generated * @param string $image_path * @param string $clone_path * @param array $params * @return array */ function calculate_image_clone_result($image_path, $clone_path, $params) { $width = isset($params['width']) ? $params['width'] : NULL; $height = isset($params['height']) ? $params['height'] : NULL; $quality = isset($params['quality']) ? $params['quality'] : NULL; $type = isset($params['type']) ? $params['type'] : NULL; $crop = isset($params['crop']) ? $params['crop'] : NULL; $watermark = isset($params['watermark']) ? $params['watermark'] : NULL; $rotation = isset($params['rotation']) ? $params['rotation'] : NULL; $reflection = isset($params['reflection']) ? $params['reflection'] : NULL; $crop_frame = isset($params['crop_frame']) ? $params['crop_frame'] : NULL; $result = NULL; // Ensure we have a valid image if ($image_path && @file_exists($image_path)) { // Ensure target directory exists, but only create 1 subdirectory $image_dir = dirname($image_path); $clone_dir = dirname($clone_path); $image_extension = pathinfo($image_path, PATHINFO_EXTENSION); $image_extension_str = null; $clone_extension = pathinfo($clone_path, PATHINFO_EXTENSION); $clone_extension_str = null; if ($image_extension != null) { $image_extension_str = '.' . $image_extension; } if ($clone_extension != null) { $clone_extension_str = '.' . $clone_extension; } $image_basename = basename($image_path, $image_extension_str); $clone_basename = basename($clone_path, $clone_extension_str); // We use a default suffix as passing in null as the suffix will make WordPress use a default $clone_suffix = null; $format_list = $this->object->get_image_format_list(); $clone_format = null; // format is determined below and based on $type otherwise left to null // suffix is only used to reconstruct paths for image_resize function if (strpos($clone_basename, $image_basename) === 0) { $clone_suffix = substr($clone_basename, strlen($image_basename)); } if ($clone_suffix != null && $clone_suffix[0] == '-') { // WordPress adds '-' on its own $clone_suffix = substr($clone_suffix, 1); } // Get original image dimensions $dimensions = getimagesize($image_path); if ($width == null && $height == null) { if ($dimensions != null) { if ($width == null) { $width = $dimensions[0]; } if ($height == null) { $height = $dimensions[1]; } } else { // XXX Don't think there's any other option here but to fail miserably...use some hard-coded defaults maybe? return null; } } if ($dimensions != null) { $dimensions_ratio = $dimensions[0] / $dimensions[1]; if ($width == null) { $width = (int) round($height * $dimensions_ratio); if ($width == $dimensions[0] - 1) { $width = $dimensions[0]; } } else { if ($height == null) { $height = (int) round($width / $dimensions_ratio); if ($height == $dimensions[1] - 1) { $height = $dimensions[1]; } } } if ($width > $dimensions[0]) { $width = $dimensions[0]; } if ($height > $dimensions[1]) { $height = $dimensions[1]; } $image_format = $dimensions[2]; if ($type != null) { if (is_string($type)) { $type = strtolower($type); // Indexes in the $format_list array correspond to IMAGETYPE_XXX values appropriately if (($index = array_search($type, $format_list)) !== false) { $type = $index; if ($type != $image_format) { // Note: this only changes the FORMAT of the image but not the extension $clone_format = $type; } } } } } if ($width == null || $height == null) { // Something went wrong... return null; } $result['clone_path'] = $clone_path; $result['clone_directory'] = $clone_dir; $result['clone_suffix'] = $clone_suffix; $result['clone_format'] = $clone_format; $result['base_width'] = $dimensions[0]; $result['base_height'] = $dimensions[1]; // image_resize() has limitations: // - no easy crop frame support // - fails if the dimensions are unchanged // - doesn't support filename prefix, only suffix so names like thumbs_original_name.jpg for $clone_path are not supported // also suffix cannot be null as that will make WordPress use a default suffix...we could use an object that returns empty string from __toString() but for now just fallback to ngg generator if (FALSE) { // disabling the WordPress method for Iteration #6 // if (($crop_frame == null || !$crop) && ($dimensions[0] != $width && $dimensions[1] != $height) && $clone_suffix != null) $result['method'] = 'wordpress'; $new_dims = image_resize_dimensions($dimensions[0], $dimensions[1], $width, $height, $crop); if ($new_dims) { list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $new_dims; $width = $dst_w; $height = $dst_h; } else { $result['error'] = new WP_Error('error_getting_dimensions', __('Could not calculate resized image dimensions')); } } else { $result['method'] = 'nextgen'; $original_width = $dimensions[0]; $original_height = $dimensions[1]; $original_ratio = $original_width / $original_height; $aspect_ratio = $width / $height; $orig_ratio_x = $original_width / $width; $orig_ratio_y = $original_height / $height; if ($crop) { $algo = 'shrink'; // either 'adapt' or 'shrink' if ($crop_frame != null) { $crop_x = (int) round($crop_frame['x']); $crop_y = (int) round($crop_frame['y']); $crop_width = (int) round($crop_frame['width']); $crop_height = (int) round($crop_frame['height']); $crop_final_width = (int) round($crop_frame['final_width']); $crop_final_height = (int) round($crop_frame['final_height']); $crop_width_orig = $crop_width; $crop_height_orig = $crop_height; $crop_factor_x = $crop_width / $crop_final_width; $crop_factor_y = $crop_height / $crop_final_height; $crop_ratio_x = $crop_width / $width; $crop_ratio_y = $crop_height / $height; if ($algo == 'adapt') { // XXX not sure about this...don't use for now # $crop_width = (int) round($width * $crop_factor_x); # $crop_height = (int) round($height * $crop_factor_y); } else { if ($algo == 'shrink') { if ($crop_ratio_x < $crop_ratio_y) { $crop_width = max($crop_width, $width); $crop_height = (int) round($crop_width / $aspect_ratio); } else { $crop_height = max($crop_height, $height); $crop_width = (int) round($crop_height * $aspect_ratio); } if ($crop_width == $crop_width_orig - 1) { $crop_width = $crop_width_orig; } if ($crop_height == $crop_height_orig - 1) { $crop_height = $crop_height_orig; } } } $crop_diff_x = (int) round(($crop_width_orig - $crop_width) / 2); $crop_diff_y = (int) round(($crop_height_orig - $crop_height) / 2); $crop_x += $crop_diff_x; $crop_y += $crop_diff_y; $crop_max_x = $crop_x + $crop_width; $crop_max_y = $crop_y + $crop_height; // Check if we're overflowing borders // if ($crop_x < 0) { $crop_x = 0; } else { if ($crop_max_x > $original_width) { $crop_x -= $crop_max_x - $original_width; } } if ($crop_y < 0) { $crop_y = 0; } else { if ($crop_max_y > $original_height) { $crop_y -= $crop_max_y - $original_height; } } } else { if ($orig_ratio_x < $orig_ratio_y) { $crop_width = $original_width; $crop_height = (int) round($height * $orig_ratio_x); } else { $crop_height = $original_height; $crop_width = (int) round($width * $orig_ratio_y); } if ($crop_width == $width - 1) { $crop_width = $width; } if ($crop_height == $height - 1) { $crop_height = $height; } $crop_x = (int) round(($original_width - $crop_width) / 2); $crop_y = (int) round(($original_height - $crop_height) / 2); } $result['crop_area'] = array('x' => $crop_x, 'y' => $crop_y, 'width' => $crop_width, 'height' => $crop_height); } else { // Just constraint dimensions to ensure there's no stretching or deformations list($width, $height) = wp_constrain_dimensions($original_width, $original_height, $width, $height); } } $result['width'] = $width; $result['height'] = $height; $result['quality'] = $quality; $real_width = $width; $real_height = $height; if ($rotation && in_array(abs($rotation), array(90, 270))) { $real_width = $height; $real_height = $width; } if ($reflection) { // default for nextgen was 40%, this is used in generate_image_clone as well $reflection_amount = 40; // Note, round() would probably be best here but using the same code that C_NggLegacy_Thumbnail uses for compatibility $reflection_height = intval($real_height * ($reflection_amount / 100)); $real_height = $real_height + $reflection_height; } $result['real_width'] = $real_width; $result['real_height'] = $real_height; } return $result; }
/** * Run, forest. */ public function process($url, $width = null, $height = null, $crop = null, $single = true, $upscale = true) { // Validate inputs. if (!$url || !$width && !$height) { return false; } $upscale = true; // Caipt'n, ready to hook. if (true === $upscale) { add_filter('image_resize_dimensions', array($this, 'aq_upscale'), 10, 6); } // Define upload path & dir. $upload_info = wp_upload_dir(); $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; $http_prefix = "http://"; $https_prefix = "https://"; /* if the $url scheme differs from $upload_url scheme, make them match if the schemes differe, images don't show up. */ if (!strncmp($url, $https_prefix, strlen($https_prefix))) { //if url begins with https:// make $upload_url begin with https:// as well $upload_url = str_replace($http_prefix, $https_prefix, $upload_url); } elseif (!strncmp($url, $http_prefix, strlen($http_prefix))) { //if url begins with http:// make $upload_url begin with http:// as well $upload_url = str_replace($https_prefix, $http_prefix, $upload_url); } // Check if $img_url is local. if (false === strpos($url, $upload_url)) { return false; } // Define path of image. $rel_path = str_replace($upload_url, '', $url); $img_path = $upload_dir . $rel_path; // Check if img path exists, and is an image indeed. if (!file_exists($img_path) or !getimagesize($img_path)) { return false; } // Get image info. $info = pathinfo($img_path); $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); // Get image size after cropping. $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; // Return the original image only if it exactly fits the needed measures. if (!$dims && (null === $height && $orig_w == $width xor null === $width && $orig_h == $height xor $height == $orig_h && $width == $orig_w)) { $img_url = $url; $dst_w = $orig_w; $dst_h = $orig_h; } else { // Use this to check if cropped image already exists, so we can return that instead. $suffix = "{$dst_w}x{$dst_h}"; $dst_rel_path = str_replace('.' . $ext, '', $rel_path); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; if (!$dims || true == $crop && false == $upscale && ($dst_w < $width || $dst_h < $height)) { // Can't resize, so return false saying that the action to do could not be processed as planned. return $url; } elseif (file_exists($destfilename) && getimagesize($destfilename)) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } else { $editor = wp_get_image_editor($img_path); if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop))) { return $url; } $resized_file = $editor->save(); if (!is_wp_error($resized_file)) { $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']); $img_url = $upload_url . $resized_rel_path; } else { return $url; } } } // Okay, leave the ship. if (true === $upscale) { remove_filter('image_resize_dimensions', array($this, 'aq_upscale')); } // Return the output. if ($single) { // str return. $image = $img_url; } else { // array return. $image = array(0 => $img_url, 1 => $dst_w, 2 => $dst_h); } return $image; }
/** * Return the image URL, crop the image to the correct dimensions if required * * @return string resized image URL */ function eps_get_image_url() { // Get the image file path $file_path = get_attached_file($this->id); // load image $image = wp_get_image_editor($file_path); // editor will return an error if the path is invalid if (is_wp_error($image)) { if (is_admin()) { echo '<div id="message" class="error">'; echo "<p><strong>ERROR</strong> " . $image->get_error_message() . " Check <a href='http://codex.wordpress.org/Changing_File_Permissions' target='_blank'>file permissions</a></p>"; echo "<button class='toggle'>Show Details</button>"; echo "<div class='message' style='display: none;'><br />Slide ID: {$this->id}<pre>"; var_dump($image); echo "</pre></div>"; echo "</div>"; } return $this->url; } // get the original image size $size = $image->get_size(); $orig_width = $size['width']; $orig_height = $size['height']; // get the crop size $size = $this->eps_get_crop_dimensions($orig_width, $orig_height); $dest_width = $size['width']; $dest_height = $size['height']; // check if a resize is needed if ($dest_width == $orig_width && $dest_height == $orig_height) { return $this->url; } // image info $info = pathinfo($file_path); $dir = $info['dirname']; $ext = $info['extension']; $name = wp_basename($file_path, ".{$ext}"); $dest_file_name = "{$dir}/{$name}-{$dest_width}x{$dest_height}.{$ext}"; // URL to destination file $url = str_replace(basename($this->url), basename($dest_file_name), $this->url); // crop needed if (!file_exists($dest_file_name)) { $dims = image_resize_dimensions($orig_width, $orig_height, $dest_width, $dest_height, true); if ($dims) { list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $image->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h); } $saved = $image->save($dest_file_name); $url = str_replace(basename($this->url), basename($saved['path']), $this->url); } return $url; }