/** * Fit small image to specified bound * * @param string $src * @param string $dest * @param int $width * @param int $height * @return bool */ public function fit($src, $dest, $width, $height) { // Calculate $size = getimagesize($src); $ratio = max($width / $size[0], $height / $size[1]); $old_width = $size[0]; $old_height = $size[1]; $new_width = intval($old_width * $ratio); $new_height = intval($old_height * $ratio); // Resize @ini_set('memory_limit', apply_filters('image_memory_limit', WP_MAX_MEMORY_LIMIT)); $image = imagecreatefromstring(file_get_contents($src)); $new_image = wp_imagecreatetruecolor($new_width, $new_height); imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height); if (IMAGETYPE_PNG == $size[2] && function_exists('imageistruecolor') && !imageistruecolor($image)) { imagetruecolortopalette($new_image, false, imagecolorstotal($image)); } // Destroy old image imagedestroy($image); // Save switch ($size[2]) { case IMAGETYPE_GIF: $result = imagegif($new_image, $dest); break; case IMAGETYPE_PNG: $result = imagepng($new_image, $dest); break; default: $result = imagejpeg($new_image, $dest); break; } imagedestroy($new_image); return $result; }
protected function _resize_padded($canvas_w, $canvas_h, $canvas_color, $width, $height, $orig_w, $orig_h, $origin_x, $origin_y) { $src_x = $src_y = 0; $src_w = $orig_w; $src_h = $orig_h; $cmp_x = $orig_w / $width; $cmp_y = $orig_h / $height; // calculate x or y coordinate and width or height of source if ($cmp_x > $cmp_y) { $src_w = round($orig_w / $cmp_x * $cmp_y); $src_x = round(($orig_w - $orig_w / $cmp_x * $cmp_y) / 2); } else { if ($cmp_y > $cmp_x) { $src_h = round($orig_h / $cmp_y * $cmp_x); $src_y = round(($orig_h - $orig_h / $cmp_y * $cmp_x) / 2); } } $resized = wp_imagecreatetruecolor($canvas_w, $canvas_h); if ($canvas_color === 'transparent') { $color = imagecolorallocatealpha($resized, 255, 255, 255, 127); } else { $rgb = cnColor::rgb2hex2rgb($canvas_color); $color = imagecolorallocatealpha($resized, $rgb['red'], $rgb['green'], $rgb['blue'], 0); } // Fill the background of the new image with allocated color. imagefill($resized, 0, 0, $color); // Restore transparency. imagesavealpha($resized, TRUE); imagecopyresampled($resized, $this->image, $origin_x, $origin_y, $src_x, $src_y, $width, $height, $src_w, $src_h); if (is_resource($resized)) { $this->update_size($width, $height); return $resized; } return new WP_Error('image_resize_error', __('Image resize failed.', 'connections'), $this->file); }
/** * Crop an Image to a given size. * * @since 2.1.0 * * @param string|int $src_file The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w The destination width. * @param int $dst_h The destination height. * @param int $src_abs Optional. If the source crop points are absolute. * @param string $dst_file Optional. The destination file to write to. * @return string New filepath on success, String error message on failure. */ function wp_crop_image($src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false) { if (is_numeric($src_file)) { // Handle int as attachment ID $src_file = get_attached_file($src_file); } $src = wp_load_image($src_file); if (!is_resource($src)) { return $src; } $dst = wp_imagecreatetruecolor($dst_w, $dst_h); if ($src_abs) { $src_w -= $src_x; $src_h -= $src_y; } if (function_exists('imageantialias')) { imageantialias($dst, true); } imagecopyresampled($dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); imagedestroy($src); // Free up memory if (!$dst_file) { $dst_file = str_replace(basename($src_file), 'cropped-' . basename($src_file), $src_file); } $dst_file = preg_replace('/\\.[^\\.]+$/', '.jpg', $dst_file); if (imagejpeg($dst, $dst_file, apply_filters('jpeg_quality', 90, 'wp_crop_image'))) { return $dst_file; } else { return false; } }
/** * Crop an Image to a given size. * * @since 2.1.0 * * @param string|int $src The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w The destination width. * @param int $dst_h The destination height. * @param int $src_abs Optional. If the source crop points are absolute. * @param string $dst_file Optional. The destination file to write to. * @return string|WP_Error|false New filepath on success, WP_Error or false on failure. */ function wp_crop_image($src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false) { if (0 == $src_x && 0 == $src_y && $src_w == $dst_w && $src_h == $dst_h) { return is_numeric($src) ? get_attached_file($src) : $src; } if (is_numeric($src)) { // Handle int as attachment ID $src_file = get_attached_file($src); if (!file_exists($src_file)) { // If the file doesn't exist, attempt a url fopen on the src link. // This can occur with certain file replication plugins. $post = get_post($src); $image_type = $post->post_mime_type; $src = load_image_to_edit($src, $post->post_mime_type, 'full'); } else { $size = @getimagesize($src_file); $image_type = $size ? $size['mime'] : ''; $src = wp_load_image($src_file); } } else { $size = @getimagesize($src); $image_type = $size ? $size['mime'] : ''; $src = wp_load_image($src); } if (!is_resource($src)) { return new WP_Error('error_loading_image', $src, $src_file); } $dst = wp_imagecreatetruecolor($dst_w, $dst_h); if ($src_abs) { $src_w -= $src_x; $src_h -= $src_y; } if (function_exists('imageantialias')) { imageantialias($dst, true); } imagecopyresampled($dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); imagedestroy($src); // Free up memory if (!$dst_file) { $dst_file = str_replace(basename($src_file), 'cropped-' . basename($src_file), $src_file); } if ('image/png' != $image_type) { $dst_file = preg_replace('/\\.[^\\.]+$/', '.jpg', $dst_file); } // The directory containing the original file may no longer exist when // using a replication plugin. wp_mkdir_p(dirname($dst_file)); if ('image/png' == $image_type && imagepng($dst, $dst_file)) { return $dst_file; } elseif (imagejpeg($dst, $dst_file, apply_filters('jpeg_quality', 90, 'wp_crop_image'))) { return $dst_file; } else { return false; } }
/** * Crops Image. * * @since 3.5.0 * @access public * * @param string|int $src The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w Optional. The destination width. * @param int $dst_h Optional. The destination height. * @param boolean $src_abs Optional. If the source crop points are absolute. * @return boolean|WP_Error */ public function crop($src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false) { $ar = $src_w / $src_h; $dst_ar = $dst_w / $dst_h; if (isset($_GET['pte-fit-crop-color']) && abs($ar - $dst_ar) > 0.01) { PteLogger::debug(sprintf("AR: '%f'\tOAR: '%f'", $ar, $dst_ar)); // Crop the image to the correct aspect ratio... if ($dst_ar > $ar) { // constrain to the dst_h $tmp_dst_h = $dst_h; $tmp_dst_w = $dst_h * $ar; $tmp_dst_y = 0; $tmp_dst_x = $dst_w / 2 - $tmp_dst_w / 2; } else { $tmp_dst_w = $dst_w; $tmp_dst_h = $dst_w / $ar; $tmp_dst_x = 0; $tmp_dst_y = $dst_h / 2 - $tmp_dst_h / 2; } // copy $this->image unto a new image with the right width/height. $img = wp_imagecreatetruecolor($dst_w, $dst_h); if (function_exists('imageantialias')) { imageantialias($img, true); } if (preg_match("/^#[a-fA-F0-9]{6}\$/", $_GET['pte-fit-crop-color'])) { $c = self::getRgbFromHex($_GET['pte-fit-crop-color']); $color = imagecolorallocate($img, $c[0], $c[1], $c[2]); } else { PteLogger::debug("setting transparent/white"); //$color = imagecolorallocate( $img, 100, 100, 100 ); $color = imagecolorallocatealpha($img, 255, 255, 255, 127); } imagefilledrectangle($img, 0, 0, $dst_w, $dst_h, $color); imagecopyresampled($img, $this->image, $tmp_dst_x, $tmp_dst_y, $src_x, $src_y, $tmp_dst_w, $tmp_dst_h, $src_w, $src_h); if (is_resource($img)) { imagedestroy($this->image); $this->image = $img; $this->update_size(); return true; } return new WP_Error('image_crop_error', __('Image crop failed.'), $this->file); } return parent::crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs); }
/** * Catch the file upload and parse it * * @since 0.1 * * @param int $post_id * @return string The filepath */ public static function catch_upload($post_id) { if (!wp_attachment_is_image($post_id)) { return; } // Get default options for Large Size Media and options $max_width = (int) get_option('large_size_w', 1024); $max_height = (int) get_option('large_size_h', 1024); $crop = (bool) get_option('media_features_crop', false); $resizes = (bool) get_option('media_features_resize', false); // If option is not enabled return if (!$resizes) { return; } // Let's see if these sizes are reasonable if ($max_width < 0 || $max_height < 0) { return; } // Get file and image GD resource $file = get_attached_file($post_id); $image = wp_load_image($file); if (!is_resource($image)) { return new WP_Error('error_loading_image', $image, $file); } // Get real dimensions from file image list($orig_width, $orig_height, $orig_type) = @getimagesize($file); // if the image needs to be cropped, resize it if ($max_width >= $orig_width && $max_height >= $orig_height) { return; } //var_dump( $file, $orig_width, $orig_height, $orig_type, $max_width, $max_height ); $dims = image_resize_dimensions($orig_width, $orig_height, $max_width, $max_height, $crop); if (!$dims) { return new WP_Error('error_getting_dimensions', __('Could not calculate resized image dimensions', 'media-features')); } 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); extract(pathinfo($file)); $name = wp_basename($file, ".{$extension}"); //var_dump( $name, $dirname, $extension ); $dirname = realpath($dirname); $dest_file = "{$dirname}/{$name}.{$extension}"; // If the file is not writable should not proceed if (!is_writeable($dest_file)) { return; } // Save to file based on original type $did_save = false; switch ($orig_type) { case IMAGETYPE_GIF: imagegif($newimage, $dest_file); break; case IMAGETYPE_PNG: imagepng($newimage, $dest_file); break; case IMAGETYPE_JPEG: case IMAGETYPE_JPEG2000: imagejpeg($newimage, $dest_file, apply_filters('jpeg_quality', 90, 'image_resize')); break; default: $dest_file = "{$dirname}/{$name}.{$extension}"; } imagedestroy($newimage); // Set correct file permissions $stat = stat(dirname($dest_file)); $perms = $stat['mode'] & 0666; //same permissions as parent folder, strip off the executable bits @chmod($dest_file, $perms); return $dest_file; }
function wp_save_image($post_id) { $msg = ''; $success = $delete = $full_resized = false; $post = get_post($post_id); @ini_set('memory_limit', '256M'); $img = load_image_to_edit($post); if (!is_resource($img)) { return 'error=' . __('Unable to create new image.'); } $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0; $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0; $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : ''; if (!empty($_REQUEST['history'])) { $changes = json_decode(stripslashes($_REQUEST['history'])); if ($changes) { $img = image_edit_apply_changes($img, $changes); } } if ($fwidth > 0 && $fheight > 0) { // scale the full size image $dst = wp_imagecreatetruecolor($fwidth, $fheight); if (imagecopyresampled($dst, $img, 0, 0, 0, 0, $fwidth, $fheight, imagesx($img), imagesy($img))) { imagedestroy($img); $img = $dst; $full_resized = true; } } if (!$changes && !$full_resized) { return 'error=' . __('Nothing to save, the image is not changed.'); } $meta = wp_get_attachment_metadata($post_id, false, false); if (!is_array($meta)) { $meta = array(); } if (!isset($meta['sizes']) || !is_array($meta['sizes'])) { $meta['sizes'] = array(); } // generate new filename $path = get_attached_file($post_id); $path_parts = pathinfo52($path); $filename = $path_parts['filename']; $suffix = time() . rand(100, 999); while (true) { $filename = preg_replace('/-e([0-9]+)$/', '', $filename); $filename .= "-e{$suffix}"; $new_filename = "{$filename}.{$path_parts['extension']}"; $new_path = "{$path_parts['dirname']}/{$new_filename}"; if (file_exists($new_path)) { $suffix++; } else { break; } } // save the full-size file, also needed to create sub-sizes if (!wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id)) { return 'error=' . __('Unable to save the image.'); } if ('full' == $target || 'all' == $target || $full_resized) { $meta['sizes']["backup-{$suffix}-full"] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']); $success = update_attached_file($post_id, $new_path); $meta['file'] = get_attached_file($post_id, true); // get the path unfiltered $meta['width'] = imagesx($img); $meta['height'] = imagesy($img); list($uwidth, $uheight) = wp_shrink_dimensions($meta['width'], $meta['height']); $meta['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; if ($success && $target == 'all') { $sizes = apply_filters('intermediate_image_sizes', array('large', 'medium', 'thumbnail')); } $msg .= "full={$meta['width']}x{$meta['height']}!"; } elseif (array_key_exists($target, $meta['sizes'])) { $sizes = array($target); $success = $delete = true; } if (isset($sizes)) { foreach ($sizes as $size) { if (isset($meta['sizes'][$size])) { $meta['sizes']["backup-{$suffix}-{$size}"] = $meta['sizes'][$size]; } $resized = image_make_intermediate_size($new_path, get_option("{$size}_size_w"), get_option("{$size}_size_h"), get_option("{$size}_crop")); if ($resized) { $meta['sizes'][$size] = $resized; } else { unset($meta['sizes'][$size]); } } } if ($success) { wp_update_attachment_metadata($post_id, $meta); if ($target == 'thumbnail' || $target == 'all' || $target == 'full' && !array_key_exists('thumbnail', $meta['sizes'])) { if ($thumb_url = get_attachment_icon_src($post_id)) { $msg .= "thumbnail={$thumb_url[0]}"; } } } else { $delete = true; } if ($delete) { $delpath = apply_filters('wp_delete_file', $new_path); @unlink($delpath); } imagedestroy($img); return $msg; }
/** * 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 95. Image quality percentage. * @return mixed WP_Error on failure. String with new destination path. */ function resize( $max_w, $max_h, $crop = false, $zoom_if_need=true) { if ( !is_resource( $this->orig_image ) ) { $this -> error_msg ('Error: orig_image not loaded'); return FALSE; } //list($orig_w, $orig_h, $orig_type) = $this->size; $orig_w=$this->orig_w; $orig_h=$this->orig_h; $orig_type=$this->orig_type; if ( $orig_w == $max_w && $orig_h == $max_h ) return TRUE; //echo $orig_w.' x '.$orig_h.'<br />';echo $max_w.' x '.$max_h.'<br />'; $dims = $this->image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop, $zoom_if_need); if ( !$dims ) { $this -> error_msg ( 'error_getting_dimensions - Could not calculate resized image dimensions', false ); return FALSE; } list($dest_x, $dest_y, $src_x, $src_y, $dest_w, $dest_h, $src_w, $src_h) = $dims; if (isset($GLOBALS['wp'])) $this->dest_image = wp_imagecreatetruecolor( $dest_w, $dest_h ); else $this->dest_image = imagecreatetruecolor( $dest_w, $dest_h ); imagecopyresampled( $this->dest_image, $this->orig_image, $dest_x, $dest_y, $src_x, $src_y, $dest_w, $dest_h, $src_w, $src_h); $this->dest_w=$dest_w; $this->dest_h=$dest_h; // convert from full colors to index colors, like original PNG. if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $this->orig_image ) ) imagetruecolortopalette( $this->dest_image, false, imagecolorstotal( $this->orig_image ) ); // we don't need the original in memory anymore - depricated //imagedestroy( $this->orig_image ); return TRUE; }
/** * Crop an Image to a given size. * Modified version of the function wp_crop_image located in * wp-admin/includes/image.php * * Mixes in some picture detection and treatment from image_resize in * wp-includes/media.php * * @param string|int $src_file The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w The destination width. * @param int $dst_h The destination height. * @param int $src_abs Optional. If the source crop points are absolute. * @param string $dst_file Optional. The destination file to write to. * @return string|WP_Error|false New filepath on success, WP_Error or false on failure. */ function ifp_wp_crop_image($src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false) { if (is_numeric($src_file)) { // Handle int as attachment ID $src_file = get_attached_file($src_file); } $src = wp_load_image($src_file); if (!is_resource($src)) { return new WP_Error('error_loading_image', $src, $src_file); } /* Part from image_resize */ $size = @getimagesize($src_file); if (!$size) { return new WP_Error('invalid_image', __('Could not read image size'), $file); } list($orig_w, $orig_h, $orig_type) = $size; /* End part from image_resize */ $dst = wp_imagecreatetruecolor($dst_w, $dst_h); if ($src_abs) { $src_w -= $src_x; $src_h -= $src_y; } imagecopyresampled($dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); /* Part from image_resize */ // convert from full colors to index colors, like original PNG. if (IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor($src)) { imagetruecolortopalette($dst, false, imagecolorstotal($src)); } /* End part from image_resize */ imagedestroy($src); // Free up memory if (!$dst_file) { $dst_file = str_replace(basename($src_file), 'cropped-' . basename($src_file), $src_file); } $info_src = pathinfo($src_file); $info_dst = pathinfo($dst_file); $dir = $info_dst['dirname']; $ext = $info_src['extension']; // Keep the source extension $name = wp_basename($dst_file, ".{$info_dst['extension']}"); $dst_file = "{$dir}/{$name}.{$ext}"; if (IMAGETYPE_GIF == $orig_type) { $success = imagegif($dst, $dst_file); } else { if (IMAGETYPE_PNG == $orig_type) { $success = imagepng($dst, $dst_file); } else { $dst_file = "{$dir}/{$name}.jpg"; $success = imagejpeg($dst, $dst_file, apply_filters('jpeg_quality', 90, 'wp_crop_image')); } } imagedestroy($dst); if ($success) { /* Part from image_resize */ // Set correct file permissions $stat = stat(dirname($dst_file)); $perms = $stat['mode'] & 0666; //same permissions as parent folder, strip off the executable bits @chmod($dst_file, $perms); /* End part from image_resize */ return $dst_file; } else { return false; } }
function gllr_image_resize($file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90) { $size = @getimagesize($file); if (!$size) { return new WP_Error('invalid_image', __('Image size not defined', 'gallery-plugin'), $file); } $type = $size[2]; if (3 == $type) { $image = imagecreatefrompng($file); } else { if (2 == $type) { $image = imagecreatefromjpeg($file); } else { if (1 == $type) { $image = imagecreatefromgif($file); } else { if (15 == $type) { $image = imagecreatefromwbmp($file); } else { if (16 == $type) { $image = imagecreatefromxbm($file); } else { return new WP_Error('invalid_image', __('We can update only PNG, JPEG, GIF, WPMP or XBM filetype. For other, please, manually reload image.', 'gallery-plugin'), $file); } } } } } if (!is_resource($image)) { return new WP_Error('error_loading_image', $image, $file); } /*$size = @getimagesize( $file );*/ list($orig_w, $orig_h, $orig_type) = $size; $dims = gllr_image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop); if (!$dims) { return new WP_Error('error_getting_dimensions', __('Image size changes not defined', 'gallery-plugin')); } 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 = wp_basename($file, ".{$ext}"); 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', __('Invalid path', 'gallery-plugin')); } } elseif (IMAGETYPE_PNG == $orig_type) { if (!imagepng($newimage, $destfilename)) { return new WP_Error('resize_path_invalid', __('Invalid path', 'gallery-plugin')); } } 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', __('Invalid path', 'gallery-plugin')); } } 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; }
/** * Crops an image resource. Internal use only. * * @since 2.9.0 * * @ignore * @param resource $img Image resource. * @param float $x Source point x-coordinate. * @param float $y Source point y-cooredinate. * @param float $w Source width. * @param float $h Source height. * @return resource (maybe) cropped image resource. */ function _crop_image_resource($img, $x, $y, $w, $h) { $dst = wp_imagecreatetruecolor($w, $h); if (is_resource($dst)) { if (imagecopy($dst, $img, 0, 0, $x, $y, $w, $h)) { imagedestroy($img); $img = $dst; } } return $img; }
/** * LazyestImage::crop() * * @param mixed $size Width and Height of the square cropped image * @return bool success or failure * @todo merge with LazyestImage::resize() */ function crop($size) { if (false === $this->loc()) { return false; } if (!$this->memory_ok()) { return false; } $img_location = $this->original(); list($o_width, $o_height, $o_type) = @getimagesize($img_location); $img = $this->load_image($img_location); if (!is_resource($img)) { trigger_error($img, E_USER_WARNING); return false; } if ($o_width > $o_height) { // landscape image $out_width = $out_height = $o_height; $out_left = round(($o_width - $o_height) / 2); $out_top = 0; } else { // portrait image $out_top = 0; $out_width = $out_height = $o_width; $out_left = 0; } $cropped = wp_imagecreatetruecolor($size, $size); imagecopyresampled($cropped, $img, 0, 0, $out_left, $out_top, $size, $size, $out_width, $out_height); // convert from full colors to index colors, like original PNG. if (IMAGETYPE_PNG == $o_type && function_exists('imageistruecolor') && !imageistruecolor($img)) { imagetruecolortopalette($cropped, false, imagecolorstotal($img)); } unset($img); $this->resized = $cropped; $this->reset_orientation(); $this->resized = apply_filters('lazyest_image_cropped', $this->resized, $size, $this); return true; }
/** * Flips current image. * * @since 3.5.0 * @access public * * @param boolean $horz Flip along Horizontal Axis * @param boolean $vert Flip along Vertical Axis * @returns boolean|WP_Error */ public function flip($horz, $vert) { $w = $this->size['width']; $h = $this->size['height']; $dst = wp_imagecreatetruecolor($w, $h); if (is_resource($dst)) { $sx = $vert ? $w - 1 : 0; $sy = $horz ? $h - 1 : 0; $sw = $vert ? -$w : $w; $sh = $horz ? -$h : $h; if (imagecopyresampled($dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh)) { imagedestroy($this->image); $this->image = $dst; return true; } } return new WP_Error('image_flip_error', __('Image flip failed.'), $this->file); }
function wp_save_image($post_id) { $return = new stdClass(); $success = $delete = $scaled = $nocrop = false; $post = get_post($post_id); @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT)); $img = load_image_to_edit($post_id, $post->post_mime_type); if (!is_resource($img)) { $return->error = esc_js(__('Unable to create new image.')); return $return; } $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0; $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0; $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : ''; $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do']; if ($scale && $fwidth > 0 && $fheight > 0) { $sX = imagesx($img); $sY = imagesy($img); // check if it has roughly the same w / h ratio $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2); if (-0.1 < $diff && $diff < 0.1) { // scale the full size image $dst = wp_imagecreatetruecolor($fwidth, $fheight); if (imagecopyresampled($dst, $img, 0, 0, 0, 0, $fwidth, $fheight, $sX, $sY)) { imagedestroy($img); $img = $dst; $scaled = true; } } if (!$scaled) { $return->error = esc_js(__('Error while saving the scaled image. Please reload the page and try again.')); return $return; } } elseif (!empty($_REQUEST['history'])) { $changes = json_decode(stripslashes($_REQUEST['history'])); if ($changes) { $img = image_edit_apply_changes($img, $changes); } } else { $return->error = esc_js(__('Nothing to save, the image has not changed.')); return $return; } $meta = wp_get_attachment_metadata($post_id); $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true); if (!is_array($meta)) { $return->error = esc_js(__('Image data does not exist. Please re-upload the image.')); return $return; } if (!is_array($backup_sizes)) { $backup_sizes = array(); } // generate new filename $path = get_attached_file($post_id); $path_parts = pathinfo($path); $filename = $path_parts['filename']; $suffix = time() . rand(100, 999); if (defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) { if ('thumbnail' == $target) { $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}"; } else { $new_path = $path; } } else { while (true) { $filename = preg_replace('/-e([0-9]+)$/', '', $filename); $filename .= "-e{$suffix}"; $new_filename = "{$filename}.{$path_parts['extension']}"; $new_path = "{$path_parts['dirname']}/{$new_filename}"; if (file_exists($new_path)) { $suffix++; } else { break; } } } // save the full-size file, also needed to create sub-sizes if (!wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id)) { $return->error = esc_js(__('Unable to save the image.')); return $return; } if ('nothumb' == $target || 'all' == $target || 'full' == $target || $scaled) { $tag = false; if (isset($backup_sizes['full-orig'])) { if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) { $tag = "full-{$suffix}"; } } else { $tag = 'full-orig'; } if ($tag) { $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']); } $success = update_attached_file($post_id, $new_path); $meta['file'] = _wp_relative_upload_path($new_path); $meta['width'] = imagesx($img); $meta['height'] = imagesy($img); list($uwidth, $uheight) = wp_constrain_dimensions($meta['width'], $meta['height'], 128, 96); $meta['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; if ($success && ('nothumb' == $target || 'all' == $target)) { $sizes = get_intermediate_image_sizes(); if ('nothumb' == $target) { $sizes = array_diff($sizes, array('thumbnail')); } } $return->fw = $meta['width']; $return->fh = $meta['height']; } elseif ('thumbnail' == $target) { $sizes = array('thumbnail'); $success = $delete = $nocrop = true; } if (isset($sizes)) { foreach ($sizes as $size) { $tag = false; if (isset($meta['sizes'][$size])) { if (isset($backup_sizes["{$size}-orig"])) { if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes["{$size}-orig"]['file'] != $meta['sizes'][$size]['file']) { $tag = "{$size}-{$suffix}"; } } else { $tag = "{$size}-orig"; } if ($tag) { $backup_sizes[$tag] = $meta['sizes'][$size]; } } $crop = $nocrop ? false : get_option("{$size}_crop"); $resized = image_make_intermediate_size($new_path, get_option("{$size}_size_w"), get_option("{$size}_size_h"), $crop); if ($resized) { $meta['sizes'][$size] = $resized; } else { unset($meta['sizes'][$size]); } } } if ($success) { wp_update_attachment_metadata($post_id, $meta); update_post_meta($post_id, '_wp_attachment_backup_sizes', $backup_sizes); if ($target == 'thumbnail' || $target == 'all' || $target == 'full') { $file_url = wp_get_attachment_url($post_id); if ($thumb = $meta['sizes']['thumbnail']) { $return->thumbnail = path_join(dirname($file_url), $thumb['file']); } else { $return->thumbnail = "{$file_url}?w=128&h=128"; } } } else { $delete = true; } if ($delete) { $delpath = apply_filters('wp_delete_file', $new_path); @unlink($delpath); } imagedestroy($img); $return->msg = esc_js(__('Image saved')); return $return; }
/** * Получение аватара пользователя * @param $u_user * @param $user_id * @return string */ function ulogin_get_user_photo($u_user, $user_id) { $q = true; $validate_gravatar = ulogin_validate_gravatar('', $user_id); if ($validate_gravatar) { update_user_meta($user_id, 'ulogin_photo_gravatar', 1); return false; } delete_user_meta($user_id, 'ulogin_photo_gravatar'); $u_user['photo'] = $u_user['photo'] === "https://ulogin.ru/img/photo.png" ? '' : $u_user['photo']; $u_user['photo_big'] = $u_user['photo_big'] === "https://ulogin.ru/img/photo_big.png" ? '' : $u_user['photo_big']; $file_url = (isset($u_user['photo_big']) and !empty($u_user['photo_big'])) ? $u_user['photo_big'] : ((isset($u_user['photo']) and !empty($u_user['photo'])) ? $u_user['photo'] : ''); if (empty($file_url)) { return false; } //directory to import to $avatar_dir = str_replace('\\', '/', dirname(dirname(dirname(dirname(__FILE__))))) . '/wp-content/uploads/'; if (!file_exists($avatar_dir)) { $q = mkdir($avatar_dir); } $avatar_dir .= 'ulogin_avatars/'; if ($q && !file_exists($avatar_dir)) { $q = mkdir($avatar_dir); } if (!$q) { return false; } $response = ulogin_get_response($file_url, false); $response = !$response && in_array('curl', get_loaded_extensions()) ? file_get_contents($file_url) : $response; if (!$response) { return false; } $filename = $u_user['network'] . '_' . $u_user['uid']; $file_addr = $avatar_dir . $filename; $handle = fopen($file_addr, "w"); $fileSize = fwrite($handle, $response); fclose($handle); if (!$fileSize) { @unlink($file_addr); return false; } list($width, $height, $type) = getimagesize($file_addr); if ($width / $height > 1) { $max_size = $width; } else { $max_size = $height; } $thumb = wp_imagecreatetruecolor($max_size, $max_size); if (!is_resource($thumb)) { @unlink($file_addr); return false; } switch ($type) { case IMAGETYPE_GIF: $res = '.gif'; $source = imagecreatefromgif($file_addr); break; case IMAGETYPE_JPEG: $res = '.jpg'; $source = imagecreatefromjpeg($file_addr); break; case IMAGETYPE_PNG: $res = '.png'; $source = imagecreatefrompng($file_addr); break; default: $res = '.jpg'; $source = imagecreatefromjpeg($file_addr); break; } if (imagecopy($thumb, $source, ($max_size - $width) / 2, ($max_size - $height) / 2, 0, 0, $width, $height)) { imagedestroy($source); @unlink($file_addr); } else { @unlink($file_addr); return false; } $filename = $filename . $res; switch ($type) { case IMAGETYPE_GIF: imagegif($thumb, $avatar_dir . $filename); break; case IMAGETYPE_JPEG: imagejpeg($thumb, $avatar_dir . $filename); break; case IMAGETYPE_PNG: imagepng($thumb, $avatar_dir . $filename); break; default: imagejpeg($thumb, $avatar_dir . $filename); break; } imagedestroy($thumb); return home_url() . '/wp-content/uploads/ulogin_avatars/' . $filename; }
function ocmx_custom_resize($file, $max_w = 0, $max_h = 0, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 100) { $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'), $file); } list($orig_w, $orig_h, $orig_type) = $size; if ($max_h == 0) { $max_h = $orig_h; } if ($max_w == 0) { $max_w = $orig_w; } if ($orig_w > $max_w || $orig_h > $max_h) { $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop); } if (!$dims) { $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; } if (strpos($dest_path, "ocmx") !== false) { copy($file, "{$dir}/{$name}.{$ext}"); } } else { 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); $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}.{$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 $destfilename = "{$dir}/{$name}.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 process() { global $plugin_page; if (isset($_GET['reset'])) { $uploaddir = ub_wp_upload_dir(); $login_image_dir = ub_get_option('ub_login_image_dir', false); if ($login_image_dir && file_exists($login_image_dir)) { $this->remove_file($login_image_dir); } ub_delete_option('ub_login_image_dir'); ub_delete_option('ub_login_image_url'); } elseif (!empty($_FILES['login_form_image_file']['name'])) { $uploaddir = ub_wp_upload_dir(); $uploadurl = ub_wp_upload_url(); $uploaddir = untrailingslashit($uploaddir); $uploadurl = untrailingslashit($uploadurl); $login_image_dir = ub_get_option('ub_login_image_dir', false); if ($login_image_dir && file_exists($login_image_dir)) { $this->remove_file($login_image_dir); } if (!is_dir($uploaddir . '/ultimate-branding/includes/login-image/')) { wp_mkdir_p($uploaddir . '/ultimate-branding/includes/login-image/'); } $file = $uploaddir . '/ultimate-branding/includes/login-image/' . basename($_FILES['login_form_image_file']['name']); $this->remove_file($file); if (!move_uploaded_file($_FILES['login_form_image_file']['tmp_name'], $file)) { wp_redirect(add_query_arg('error', 'true', wp_get_referer())); } @chmod($file, 0777); if (!function_exists('imagecreatefromstring')) { return __('The GD image library is not installed.'); } // Set artificially high because GD uses uncompressed images in memory @ini_set('memory_limit', '256M'); $image = imagecreatefromstring(file_get_contents($file)); if (!is_resource($image)) { wp_redirect(add_query_arg('error', 'true', wp_get_referer())); } $size = @getimagesize($file); if (!$size) { wp_redirect(add_query_arg('error', 'true', wp_get_referer())); } list($orig_w, $orig_h, $orig_type) = $size; $dims = image_resize_dimensions($orig_w, $orig_h, 326, 0, false); 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 = 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); if (!imagepng($newimage, $uploaddir . '/ultimate-branding/includes/login-image/login-form-image.png')) { wp_redirect(add_query_arg('error', 'true', wp_get_referer())); } imagedestroy($newimage); $stat = stat($uploaddir . '/ultimate-branding/includes/login-image/'); $perms = $stat['mode'] & 0666; //same permissions as parent folder, strip off the executable bits @chmod($uploaddir . '/ultimate-branding/includes/login-image/login-form-image.png', $perms); $this->remove_file($file); ub_update_option('ub_login_image_dir', $uploaddir . '/ultimate-branding/includes/login-image/login-form-image.png'); ub_update_option('ub_login_image_url', $uploadurl . '/ultimate-branding/includes/login-image/login-form-image.png'); } return true; }
protected function _resize_2x($new_size, $crop) { $dims = image_resize_dimensions($this->size['width'], $this->size['height'], $new_size['width'], $new_size['height'], $crop); if (!$dims) { return new WP_Error('error_getting_dimensions', __('Image resize failed.', 'wphidpi'), $this->file); } list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; // Unique to _resize_2x $dst_w *= 2; $dst_h *= 2; $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.', 'wphidpi'), $this->file); }
function rt_get_thumbnail_from_image_url($image_url, $max_w, $max_h, $crop) { //caculate md5 of $image_url //as we are processing full URLs, www, non-www, change in domains >> will invalidate cache. //But such big changes are very rare. So for speed and accuracy we will take loose route $cache_key = md5($image_url . $max_w . $max_h . $crop); $cache_file = $cache_key . "." . pathinfo(parse_url($image_url, PHP_URL_PATH), PATHINFO_EXTENSION); $cache_file_path = RT_CACHE_DIR_PATH . $cache_file; //absoulte path to file $cache_file_url = RT_CACHE_DIR_URL . $cache_file; //weburl to cached thumbnail //check if thumbnail is present in cache if (file_exists($cache_file_path)) { //cache HIT return $cache_file_url; } //cache check failed :-( //before going ahead lets check if cache path is writable as of now, otherwise our efforts will go waste //suggestion by Phil(@frumph) if (!is_writable(dirname($cache_file_path))) { return FALSE; } //download image and cache its thumbnail version if (function_exists('curl_init')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $image_url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0'); $tmp_image = curl_exec($ch); if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) { //echo "Error in CURL transfer"; curl_errno($ch); return FALSE; } curl_close($ch); } //end of curl job if (!function_exists('imagecreatefromstring')) { return FALSE; } //return __('The GD image library is not installed.'); // Set artificially high because GD uses uncompressed images in memory $image = imagecreatefromstring($tmp_image); if (!is_resource($image)) { return FALSE; } //return __('error_loading_image'); $orig_type = image_file_type_from_binary($tmp_image); //get image mime type $orig_w = imagesx($image); $orig_h = imagesy($image); $dims = rt_image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop); list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; //edited by: Santosh //below conditions check if actual image size is smaller than what we expect it to resized, //then return actual image path no need to resize if ($dst_w >= $orig_w && $dst_h >= $orig_h) { return $image_url; } //if actual image width is less than dest-width then //assign max-width and dest-width values equal to actual width if ($dst_w >= $orig_w) { $max_w = $orig_w; } //if actual image height is less than dest-height then //assign max-height and dest-height values equal to actual width if ($dst_h >= $orig_h) { $max_h = $orig_h; } $cache_file = wp_imagecreatetruecolor($max_w, $max_h); //imagecopyresampled($cache_file, $image, 0, 0, $src_x, $src_y, $max_w, $max_h, $orig_w, $orig_h); imagecopyresampled($cache_file, $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($cache_file, false, imagecolorstotal($image)); } // we don't need the original in memory anymore imagedestroy($image); if (IMAGETYPE_GIF == $orig_type) { if (!imagegif($cache_file, $cache_file_path)) { return FALSE; } //return new WP_Error('resize_path_invalid', __('Resize path invalid')); } elseif (IMAGETYPE_PNG == $orig_type) { if (!imagepng($cache_file, $cache_file_path)) { return FALSE; } //return new WP_Error('resize_path_invalid', __('Resize path invalid')); } else { // all other formats are converted to jpg if (!imagejpeg($cache_file, $cache_file_path, apply_filters('jpeg_quality', 100, 'image_resize'))) { return FALSE; } //return new WP_Error('resize_path_invalid', __('Resize path invalid')); } imagedestroy($cache_file); // Set correct file permissions $stat = stat(dirname($cache_file_path)); $perms = $stat['mode'] & 0666; //same permissions as parent folder, strip off the executable bits @chmod($cache_file_path, $perms); if (file_exists($cache_file_path)) { //cache HIT return $cache_file_url; } }
function _dp_resize_logo() { $dp_resize_message = array('error' => true, 'message' => ''); //値をチェック $ratio = intval($_REQUEST['dp_resize_ratio']); if (!($ratio > 0 && $ratio <= 100)) { $ratio = 100; } $orignal_to_display_ratio = (double) $_REQUEST['dp_logo_to_resize_ratio']; $width = round($_REQUEST['dp_logo_resize_width'] / $orignal_to_display_ratio); $height = round($_REQUEST['dp_logo_resize_height'] / $orignal_to_display_ratio); $top = round($_REQUEST['dp_logo_resize_top'] / $orignal_to_display_ratio); $left = round($_REQUEST['dp_logo_resize_left'] / $orignal_to_display_ratio); $new_width = round($width * $ratio / 100); $new_height = round($height * $ratio / 100); //画像を読み込んでみる $info = dp_logo_info(); if (!$info) { $dp_resize_message['message'] = __('Logo file not exists.', 'tcd-w'); return $dp_resize_message; } // 保存ファイル名を決める $path = preg_replace("/logo\\.(png|gif|jpe?g)\$/i", "logo-resized.\$1", $info['path']); // 3.5以前と以降で処理を分岐 try { // 3.5以降はwp_get_image_editorが存在する if (function_exists('wp_get_image_editor')) { // 新APIを利用 $orig_image = wp_get_image_editor($info['path']); // 読み込み失敗ならエラー if (is_wp_error($orig_image)) { throw new Exception(__('Logo file not exists.', 'tcd-w')); } // リサイズしてダメだったらエラー $size = $orig_image->get_size(); $resize_result = $orig_image->resize(round($size['width'] * $ratio / 100), round($size['height'] * $ratio / 100)); if (is_wp_error($resize_result)) { // WordPressが返すエラーメッセージを利用 // 適宜変更してください。 throw new Exception($resize_result->get_error_message()); } // 切り抜きしてダメだったらエラー $crop_result = $orig_image->crop(round($left * $ratio / 100), round($top * $ratio / 100), $new_width, $new_height); if (is_wp_error($crop_result)) { // WordPressが返すエラーメッセージを利用 // 適宜変更してください。 throw new Exception($crop_result->get_error_message()); } // 保存してダメだったらエラー // 基本は上書きOK. $save_result = $orig_image->save($path); if (is_wp_error($save_result)) { // WordPressが返すエラーメッセージを利用 // 適宜変更してください。 throw new Exception($save_result->get_error_message()); } } else { // それ以前は昔の方法で行う $orig_image = wp_load_image($info['path']); // 画像を読み込めなかったらエラー if (!is_resource($orig_image)) { throw new Exception(__('Logo file not exists.', 'tcd-w')); } $newimage = wp_imagecreatetruecolor($new_width, $new_height); imagecopyresampled($newimage, $orig_image, 0, 0, $left, $top, $new_width, $new_height, $width, $height); if (IMAGETYPE_PNG == $info['mime'] && function_exists('imageistruecolor')) { @imagetruecolortopalette($newimage, false, imagecolorstotal($orig_image)); } imagedestroy($orig_image); //ファイルを保存する前に削除 $dest_path = dp_logo_exists(true); if ($dest_path && !@unlink($dest_path)) { throw new Exception('Cannot delete existing resized logo.', 'tcd-w'); } //名前を決めて保存 $result = null; if (IMAGETYPE_GIF == $info['mime']) { $result = imagegif($newimage, $path); } elseif (IMAGETYPE_PNG == $info['mime']) { $result = imagepng($newimage, $path); } else { $result = imagejpeg($newimage, $path, 100); } imagedestroy($newimage); if (!$result) { throw new Exception(sprintf(__('Failed to save resized logo. Please check permission of <code>%s</code>', 'tcd-w'), dp_logo_basedir())); } } } catch (Exception $e) { // 上記処理中で一回でも例外が発生したら、エラーを返す $dp_resize_message['message'] = $e->getMessage(); return $dp_resize_message; } // ここまで来たということはエラーなし $dp_resize_message['error'] = false; $dp_resize_message['message'] = __('Logo image is successfully resized.', 'tcd-w'); return $dp_resize_message; }
function pte_create_image($original_image, $type, $dst_x, $dst_y, $dst_w, $dst_h, $src_x, $src_y, $src_w, $src_h) { $logger = PteLogger::singleton(); $logger->debug(print_r(compact('type', 'dst_x', 'dst_y', 'dst_w', 'dst_h', 'src_x', 'src_y', 'src_w', 'src_h'), true)); $new_image = wp_imagecreatetruecolor($dst_w, $dst_h); imagecopyresampled($new_image, $original_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 == $type && function_exists('imageistruecolor') && !imageistruecolor($original_image)) { imagetruecolortopalette($newimage, false, imagecolorstotal($original_image)); } return $new_image; }
/** * Private resize method. * * @param type $img * @param type $destination * @param type $args * @return type */ private static function __resizeImg($img, $args = array()) { if (is_wp_error($check = self::$__utils->checkEditRequirements($img))) { return $check; } if (is_wp_error($imgData = self::$__utils->getImg($img))) { return $imgData; } if (is_wp_error($path = self::$__utils->getWritablePath($img))) { return $path; } $args = wp_parse_args($args, array('resize' => 'proportional', 'padding_color' => '#FFF', 'clear_cache' => false, 'width' => 250, 'height' => 250)); if (intval($args['width']) < 1) { $args['width'] = null; } if (intval($args['height']) < 1) { $args['height'] = null; } if ($args['width'] === null && $args['height'] === null) { return new WP_Error(__CLASS__ . '::' . __METHOD__, "Could not calculate resized image dimensions {$img}", $args); } $dims = image_resize_dimensions($imgData->width, $imgData->height, intval($args['width']), intval($args['height']), $args['resize'] == 'crop'); if (!$dims) { return new WP_Error(__CLASS__ . '::' . __METHOD__, "Could not calculate resized image dimensions {$img}", $dims); } // $__dst_w = intval($args['width']) < 1 ? $dims[4] : intval($args['width']); $__dst_h = intval($args['height']) < 1 ? $dims[5] : intval($args['height']); $basename = self::$__utils->basename($img, ".{$imgData->pathinfo['extension']}"); switch ($args['resize']) { case 'stretch': $suffix = "{$__dst_w}x{$__dst_h}-stretched"; break; case 'pad': $_padding_color_suffix = $args['padding_color'] == 'transparent' ? 'transparent' : hexdec($args['padding_color']); $suffix = "{$__dst_w}x{$__dst_h}-pad-" . $_padding_color_suffix; break; default: $suffix = "{$dims[4]}x{$dims[5]}"; break; } $croppedImg = "{$path}{$basename}-wpcf_{$suffix}.{$imgData->pathinfo['extension']}"; if (!$args['clear_cache']) { if (!is_wp_error($cropped = self::$__utils->getImg($croppedImg))) { return $cropped; } } /* * * Cropping */ $imgRes = self::$__utils->loadImg($img); if (!is_resource($imgRes)) { return new WP_Error(__CLASS__ . '::' . __METHOD__, "error_loading_image {$img}", $imgRes); } $dst_x = $dst_y = $src_x = $src_y = 0; $dst_w = intval($args['width']); $dst_h = intval($args['height']); $src_w = $imgData->width; $src_h = $imgData->height; switch ($args['resize']) { case 'stretch': $dst_w = $__dst_w; $dst_h = $__dst_h; $new_image = wp_imagecreatetruecolor($__dst_w, $__dst_h); break; case 'crop': default: list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims; $new_image = wp_imagecreatetruecolor($dst_w, $dst_h); break; case 'pad': $image_x = $imgData->width; $image_y = $imgData->height; $image_ar = $image_x / $image_y; $disp_x = $dst_w = $__dst_w; $disp_y = $dst_h = $__dst_h; $disp_ar = $disp_x / $disp_y; if ($image_ar > $disp_ar) { $ratio = $disp_x / $image_x; $dst_y = ($disp_y - $image_y * $ratio) / 2; // $offset_top $dst_h = $disp_y - $dst_y * 2; } else { $ratio = $disp_y / $image_y; $dst_x = ($disp_x - $image_x * $ratio) / 2; // $offset_left $dst_w = $disp_x - $dst_x * 2; } $new_image = wp_imagecreatetruecolor($__dst_w, $__dst_h); if ($args['padding_color'] == 'transparent') { $t = imagecolorallocatealpha($new_image, 255, 255, 255, 127); imagefill($new_image, 0, 0, $t); imagealphablending($new_image, true); } else { $rgb = self::$__utils->hex2rgb($args['padding_color']); $padding_color = imagecolorallocate($new_image, $rgb['red'], $rgb['green'], $rgb['blue']); imagefill($new_image, 0, 0, $padding_color); } break; } $success = imagecopyresampled($new_image, $imgRes, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); if (!$success) { imagedestroy($imgRes); imagedestroy($new_image); return new WP_Error(__CLASS__ . '::' . __METHOD__, "Error resampling image {$img}", $dims); } // convert from full colors to index colors, like original PNG. if (IMAGETYPE_PNG == $imgData->imagetype && function_exists('imageistruecolor') && !imageistruecolor($imgRes)) { imagetruecolortopalette($new_image, false, imagecolorstotal($imgRes)); } // we don't need the original in memory anymore imagedestroy($imgRes); try { if (IMAGETYPE_GIF == $imgData->imagetype) { if (!imagegif($new_image, $croppedImg)) { throw new Exception(); } } else { if (IMAGETYPE_PNG == $imgData->imagetype) { if (!imagepng($new_image, $croppedImg)) { throw new Exception(); } } else { // all other formats are converted to jpg if ('jpg' != strtolower($imgData->pathinfo['extension']) && 'jpeg' != strtolower($imgData->pathinfo['extension'])) { $croppedImg = basename($croppedImg, $imgData->pathinfo['extension']) . '.jpg'; } if (!imagejpeg($new_image, $croppedImg, apply_filters('jpeg_quality', 90, 'image_resize'))) { throw new Exception(); } } } } catch (Exception $e) { imagedestroy($new_image); return new WP_Error(__CLASS__ . '::' . __METHOD__, __('Resize path invalid', 'wpcf'), $croppedImg); } imagedestroy($new_image); // Set correct file permissions $stat = stat(dirname($croppedImg)); //same permissions as parent folder, strip off the executable bits $perms = $stat['mode'] & 0666; @chmod($croppedImg, $perms); return self::$__utils->getImgObject($croppedImg, $dst_w, $dst_h, $imgData->imagetype, $imgData->mime); }
protected function _resize_animated_gif($max_w, $max_h, $crop = false) { $frame_resources = array(); // GD resources of each frame $durations = array(); // ms duration of each frame $gfe = new GifFrameExtractor(); $gfe->extract($this->file); // get frames from gif $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; foreach ($gfe->getFrames() as $frame) { $img = $frame["image"]; $duration = $frame["duration"]; $frame_resize_resource = wp_imagecreatetruecolor($dst_w, $dst_h); // resize frame imagecopyresampled($frame_resize_resource, $img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); if (is_resource($frame_resize_resource)) { $frame_resources[] = $frame_resize_resource; $durations[] = $duration; } } if ($frame_resources) { $this->update_size($dst_w, $dst_h); // reconstruct small gif: $gc = new GifCreator(); $gc->create($frame_resources, $durations, 0); return $gc; } else { return new WP_Error('image_resize_error', __('Image resize failed.'), $this->file); } }
/** * 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; }
function image_upsize($file, $max_w, $max_h, $color = null, $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'), $file); } list($orig_w, $orig_h, $orig_type) = $size; $dst_x = (int) ($max_w / 2) - $orig_w / 2; $dst_y = (int) ($max_h / 2) - $orig_h / 2; $src_x = 0; $src_y = 0; $dst_w = $max_w; $dst_h = $max_h; $src_w = $orig_w; $src_h = $orig_h; $newimage = wp_imagecreatetruecolor($dst_w, $dst_h); if (!empty($color)) { $r = base_convert(substr($color, 0, 2), 16, 10); $g = base_convert(substr($color, 2, 2), 16, 10); $b = base_convert(substr($color, 4, 2), 16, 10); $background = imagecolorallocate($newimage, $r, $g, $b); imagefill($newimage, 0, 0, $background); } imagecopyresampled($newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_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 = basename($file, ".{$ext}"); if (!is_null($dest_path) && ($_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')); } } 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. $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); // Delete old image. unlink($file); return $destfilename; }
function uw_image_resize($url, $width = NULL, $height = NULL, $crop = true, $retina = false) { global $wpdb; if (empty($url)) { return new WP_Error('no_image_url', __('No image URL has been entered.', 'wta'), $url); } // Bail if GD Library doesn't exist if (!extension_loaded('gd') || !function_exists('gd_info')) { return array('url' => $url, 'width' => $width, 'height' => $height); } // Get default size from database $width = $width ? $width : get_option('thumbnail_size_w'); $height = $height ? $height : get_option('thumbnail_size_h'); // Allow for different retina sizes $retina = $retina ? $retina === true ? 2 : $retina : 1; // Destination width and height variables $dest_width = $width * $retina; $dest_height = $height * $retina; // Get image file path $file_path = parse_url($url); $file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path['path']; // Check for Multisite if (is_multisite()) { global $blog_id; $blog_details = get_blog_details($blog_id); $file_path = str_replace($blog_details->path . 'files/', '/wp-content/blogs.dir/' . $blog_id . '/files/', $file_path); } // Some additional info about the image $info = pathinfo($file_path); $dir = $info['dirname']; $ext = $info['extension']; $name = wp_basename($file_path, ".{$ext}"); if ('bmp' == $ext) { return new WP_Error('bmp_mime_type', __('Image is BMP. Please use either JPG or PNG.', 'wta'), $url); } // Suffix applied to filename $suffix = "{$dest_width}x{$dest_height}"; // Get the destination file name $dest_file_name = "{$dir}/{$name}-{$suffix}.{$ext}"; // No need to resize & create a new image if it already exists! if (!file_exists($dest_file_name)) { /* * Bail if this image isn't in the Media Library either. * We only want to resize Media Library images, so we can be sure they get deleted correctly when appropriate. */ $query = $wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE guid='%s'", $url); $get_attachment = $wpdb->get_results($query); if (!$get_attachment) { return array('url' => $url, 'width' => $width, 'height' => $height); } $image = wp_load_image($file_path); if (!is_resource($image)) { return new WP_Error('error_loading_image_as_resource', $image, $file_path); } // Get the current image dimensions and type $size = @getimagesize($file_path); if (!$size) { return new WP_Error('file_path_getimagesize_failed', __('Failed to get $file_path information using "@getimagesize".', 'wta'), $file_path); } list($orig_width, $orig_height, $orig_type) = $size; // Create new image $new_image = wp_imagecreatetruecolor($dest_width, $dest_height); // Do some proportional cropping if enabled if ($crop) { $src_x = $src_y = 0; $src_w = $orig_width; $src_h = $orig_height; $cmp_x = $orig_width / $dest_width; $cmp_y = $orig_height / $dest_height; // Calculate x or y coordinate, and width or height of source if ($cmp_x > $cmp_y) { $src_w = round($orig_width / $cmp_x * $cmp_y); $src_x = round(($orig_width - $orig_width / $cmp_x * $cmp_y) / 2); } else { if ($cmp_y > $cmp_x) { $src_h = round($orig_height / $cmp_y * $cmp_x); $src_y = round(($orig_height - $orig_height / $cmp_y * $cmp_x) / 2); } } // Create the resampled image imagecopyresampled($new_image, $image, 0, 0, $src_x, $src_y, $dest_width, $dest_height, $src_w, $src_h); } else { imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dest_width, $dest_height, $orig_width, $orig_height); } // Convert from full colors to index colors, like original PNG. if (IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor($image)) { imagetruecolortopalette($new_image, false, imagecolorstotal($image)); } // Remove the original image from memory (no longer needed) imagedestroy($image); // Check the image is the correct file type if (IMAGETYPE_GIF == $orig_type) { if (!imagegif($new_image, $dest_file_name)) { return new WP_Error('resize_path_invalid', __('Resize path invalid (GIF)', 'wta')); } } elseif (IMAGETYPE_PNG == $orig_type) { if (!imagepng($new_image, $dest_file_name)) { return new WP_Error('resize_path_invalid', __('Resize path invalid (PNG).', 'wta')); } } else { // All other formats are converted to jpg if ('jpg' != $ext && 'jpeg' != $ext) { $dest_file_name = "{$dir}/{$name}-{$suffix}.jpg"; } if (!imagejpeg($new_image, $dest_file_name, apply_filters('resize_jpeg_quality', 90))) { return new WP_Error('resize_path_invalid', __('Resize path invalid (JPG).', 'wta')); } } // Remove new image from memory (no longer needed as well) imagedestroy($new_image); // Set correct file permissions $stat = stat(dirname($dest_file_name)); $perms = $stat['mode'] & 0666; @chmod($dest_file_name, $perms); // Get some information about the resized image $new_size = @getimagesize($dest_file_name); if (!$new_size) { return new WP_Error('resize_path_getimagesize_failed', __('Failed to get $dest_file_name (resized image) info via @getimagesize', 'wta'), $dest_file_name); } list($resized_width, $resized_height, $resized_type) = $new_size; // Get the new image URL $resized_url = str_replace(basename($url), basename($dest_file_name), $url); // Add the resized dimensions to original image metadata (so we can delete our resized images when the original image is delete from the Media Library) $metadata = wp_get_attachment_metadata($get_attachment[0]->ID); if (isset($metadata['image_meta'])) { $metadata['image_meta']['resized_images'][] = $resized_width . 'x' . $resized_height; wp_update_attachment_metadata($get_attachment[0]->ID, $metadata); } // Return array with resized image information $image_array = array('url' => $resized_url, 'width' => $resized_width, 'height' => $resized_height, 'type' => $resized_type); } else { $image_array = array('url' => str_replace(basename($url), basename($dest_file_name), $url), 'width' => $dest_width, 'height' => $dest_height, 'type' => $ext); } return $image_array; }
function _dp_resize_logo() { $dp_resize_message = array('error' => true, 'message' => ''); //値をチェック $ratio = intval($_REQUEST['dp_resize_ratio']); if (!($ratio > 0 && $ratio <= 100)) { $ratio = 100; } $orignal_to_display_ratio = (double) $_REQUEST['dp_logo_to_resize_ratio']; $width = round($_REQUEST['dp_logo_resize_width'] / $orignal_to_display_ratio); $height = round($_REQUEST['dp_logo_resize_height'] / $orignal_to_display_ratio); $top = round($_REQUEST['dp_logo_resize_top'] / $orignal_to_display_ratio); $left = round($_REQUEST['dp_logo_resize_left'] / $orignal_to_display_ratio); //画像を読み込んでみる $info = dp_logo_info(); if (!$info) { $dp_resize_message['message'] = __('Logo file not exists.', 'tcd-w'); return $dp_resize_message; } $orig_image = wp_load_image($info['path']); if (!is_resource($orig_image)) { $dp_resize_message['message'] = __('Logo file not exists.', 'tcd-w'); return $dp_resize_message; } $new_width = round($width * $ratio / 100); $new_height = round($height * $ratio / 100); $newimage = wp_imagecreatetruecolor($new_width, $new_height); imagecopyresampled($newimage, $orig_image, 0, 0, $left, $top, $new_width, $new_height, $width, $height); if (IMAGETYPE_PNG == $info['mime'] && function_exists('imageistruecolor')) { @imagetruecolortopalette($newimage, false, imagecolorstotal($orig_image)); } imagedestroy($orig_image); //ファイルを保存する前に削除 $dest_path = dp_logo_exists(true); if ($dest_path && !@unlink($dest_path)) { $dp_resize_message['message'] = __('Cannot delete existing resized logo.', 'tcd-w'); return $dp_resize_message; } //名前を決めて保存 $path = preg_replace("/logo\\.(png|gif|jpe?g)\$/i", "logo-resized.\$1", $info['path']); $result = null; if (IMAGETYPE_GIF == $info['mime']) { $result = imagegif($newimage, $path); } elseif (IMAGETYPE_PNG == $info['mime']) { $result = imagepng($newimage, $path); } else { $result = imagejpeg($newimage, $path, 100); } imagedestroy($newimage); if ($result) { $dp_resize_message['error'] = false; $dp_resize_message['message'] = __('Logo image is successfully resized.', 'tcd-w'); } else { $dp_resize_message['message'] = sprintf(__('Failed to save resized logo. Please check permission of <code>%s</code>', 'tcd-w'), dp_logo_basedir()); } return $dp_resize_message; }