本文整理汇总了PHP中wp_constrain_dimensions函数的典型用法代码示例。如果您正苦于以下问题:PHP wp_constrain_dimensions函数的具体用法?PHP wp_constrain_dimensions怎么用?PHP wp_constrain_dimensions使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了wp_constrain_dimensions函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: miss_get_admin_thumbnail
function miss_get_admin_thumbnail($post_id, $max_w = 100, $max_h = 100, $noimage = 'production/images/noimage_small.jpg')
{
if (has_post_thumbnail($post_id)) {
$thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'thumbnail');
} else {
$att_query = new WP_Query(array('post_type' => 'attachment', 'post_status' => 'inherit', 'post_parent' => $post_id, 'posts_per_page' => 1, 'post_mime_type' => 'image', 'order' => 'DESC', 'orderby' => 'menu_order'));
if (count($att_query->posts)) {
$thumb = wp_get_attachment_image_src($att_query->posts[0]->ID, 'thumbnail');
} else {
$thumb = array(THEME_IMAGES_ASSETS . '/general/no-thumbnail.png', 50, 50);
}
}
if (!$thumb) {
if (!$noimage) {
return false;
}
//$thumb = 'na'; //trailingslashit( get_template_directory_uri() ) . $noimage;
$thumb = THEME_IMAGES_ASSETS . '/general/no-thumbnail.png';
$w = $max_w;
$h = $max_h;
} else {
$sizes = wp_constrain_dimensions($thumb[1], $thumb[2], $max_w, $max_h);
$w = $sizes[0];
$h = $sizes[1];
$thumb = $thumb[0];
}
return array(esc_url($thumb), $w, $h);
}
示例2: dt_metabox_benefits_options
function dt_metabox_benefits_options($post)
{
$box_name = 'dt_benefits_options';
$defaults = array('retina_image' => '', 'retina_image_w' => 0, 'retina_image_h' => 0, 'retina_image_id' => null);
$opts = get_post_meta($post->ID, '_' . $box_name, true);
$opts = wp_parse_args(maybe_unserialize($opts), $defaults);
// Use nonce for verification
wp_nonce_field(plugin_basename(__FILE__), $box_name . '_nonce');
// image
$img_id = '<input type="hidden" value="' . $opts['retina_image_id'] . '" class="dt-uploader-textfield dt-get-id" name="' . $box_name . '_retina_image_id" />';
// upload button
$upload = dt_melement('link', array('description' => _x('Upload Image', 'backend benefits', LANGUAGE_ZONE), 'class' => 'dt-uploader-opener button-primary thickbox', 'href' => get_admin_url() . 'media-upload.php?post_id=' . $post->ID . '&type=image&TB_iframe=1&width=640&height=310'));
// delete button
$delete = dt_melement('link', array('description' => _x('Clear', 'backend benefits', LANGUAGE_ZONE), 'class' => 'dt-uploader-delete button', 'href' => '#'));
?>
<p class="dt_switcher-box"><?php
if ($opts['retina_image_id']) {
$img = wp_get_attachment_image_src($opts['retina_image_id'], 'medium');
if ($img) {
$size = wp_constrain_dimensions($img[1], $img[2], 266, 266);
echo '<img class="attachment-266x266 dt-thumb" src="' . $img[0] . '" ' . image_hwstring($size[0], $size[1]) . ' />';
}
}
echo $img_id . $upload . $delete;
?>
</p>
<?php
}
示例3: imsanity_resize_image
/**
* Resizes the image with the given id according to the configured max width and height settings
* renders a json response indicating success/failure and dies
*/
function imsanity_resize_image()
{
imsanity_verify_permission();
global $wpdb;
$id = intval($_POST['id']);
if (!$id) {
$results = array('success' => false, 'message' => __('Missing ID Parameter', 'imsanity'));
echo json_encode($results);
die;
}
// @TODO: probably doesn't need the join...?
$query = $wpdb->prepare("select\n\t\t\t\t{$wpdb->posts}.ID as ID,\n\t\t\t\t{$wpdb->posts}.guid as guid,\n\t\t\t\t{$wpdb->postmeta}.meta_value as file_meta\n\t\t\t\tfrom {$wpdb->posts}\n\t\t\t\tinner join {$wpdb->postmeta} on {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id and {$wpdb->postmeta}.meta_key = %s\n\t\t\t\twhere {$wpdb->posts}.ID = %d\n\t\t\t\tand {$wpdb->posts}.post_type = %s\n\t\t\t\tand {$wpdb->posts}.post_mime_type like %s", array('_wp_attachment_metadata', $id, 'attachment', 'image%'));
$images = $wpdb->get_results($query);
if ($images) {
$image = $images[0];
$meta = unserialize($image->file_meta);
$uploads = wp_upload_dir();
$oldPath = $uploads['basedir'] . "/" . $meta['file'];
$maxW = imsanity_get_option('imsanity_max_width', IMSANITY_DEFAULT_MAX_WIDTH);
$maxH = imsanity_get_option('imsanity_max_height', IMSANITY_DEFAULT_MAX_HEIGHT);
// method one - slow but accurate, get file size from file itself
// list($oldW, $oldH) = getimagesize( $oldPath );
// method two - get file size from meta, fast but resize will fail if meta is out of sync
$oldW = $meta['width'];
$oldH = $meta['height'];
if ($oldW > $maxW && $maxW > 0 || $oldH > $maxH && $maxH > 0) {
$quality = imsanity_get_option('imsanity_quality', IMSANITY_DEFAULT_QUALITY);
list($newW, $newH) = wp_constrain_dimensions($oldW, $oldH, $maxW, $maxH);
$resizeResult = imsanity_image_resize($oldPath, $newW, $newH, false, null, null, $quality);
// $resizeResult = new WP_Error('invalid_image', __('Could not read image size'), $oldPath); // uncommend to debug fail condition
if (!is_wp_error($resizeResult)) {
$newPath = $resizeResult;
if ($newPath != $oldPath) {
// remove original and replace with re-sized image
unlink($oldPath);
rename($newPath, $oldPath);
}
$meta['width'] = $newW;
$meta['height'] = $newH;
// @TODO replace custom query with update_post_meta
$update_query = $wpdb->prepare("update {$wpdb->postmeta}\n\t\t\t\t\t\tset {$wpdb->postmeta}.meta_value = %s\n\t\t\t\t\t\twhere {$wpdb->postmeta}.post_id = %d\n\t\t\t\t\t\tand {$wpdb->postmeta}.meta_key = %s", array(maybe_serialize($meta), $image->ID, '_wp_attachment_metadata'));
$wpdb->query($update_query);
$results = array('success' => true, 'id' => $id, 'message' => sprintf(__('OK: %s', 'imsanity'), $oldPath));
} else {
$results = array('success' => false, 'id' => $id, 'message' => sprintf(__('ERROR: %s (%s)', 'imsanity'), $oldPath, htmlentities($resizeResult->get_error_message())));
}
} else {
$results = array('success' => true, 'id' => $id, 'message' => sprintf(__('SKIPPED: %s (Resize not required)', 'imsanity'), $oldPath));
}
} else {
$results = array('success' => false, 'id' => $id, 'message' => sprintf(__('ERROR: (Attachment with ID of %s not found) ', 'imsanity'), htmlentities($id)));
}
// if there is a quota we need to reset the directory size cache so it will re-calculate
delete_transient('dirsize_cache');
echo json_encode($results);
die;
// required by wordpress
}
示例4: dt_constrain_dim
/**
* Constrain dimensions helper.
*
* @param $w0 int
* @param $h0 int
* @param $w1 int
* @param $h1 int
* @param $change boolena
*
* @return array
*/
function dt_constrain_dim( $w0, $h0, &$w1, &$h1, $change = false ) {
$prop_sizes = wp_constrain_dimensions( $w0, $h0, $w1, $h1 );
if ( $change ) {
$w1 = $prop_sizes[0];
$h1 = $prop_sizes[1];
}
return array( $w1, $h1 );
}
示例5: vt_resize
function vt_resize($attach_id = null, $img_url = null, $width, $height, $crop = false)
{
// this is an attachment, so we have the ID
if ($attach_id) {
$image_src = wp_get_attachment_image_src($attach_id, 'full');
$file_path = get_attached_file($attach_id);
// this is not an attachment, let's use the image url
} else {
if ($img_url) {
$file_path = parse_url($img_url);
$file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path['path'];
//$file_path = ltrim( $file_path['path'], '/' );
//$file_path = rtrim( ABSPATH, '/' ).$file_path['path'];
$orig_size = getimagesize($file_path);
$image_src[0] = $img_url;
$image_src[1] = $orig_size[0];
$image_src[2] = $orig_size[1];
}
}
$file_info = pathinfo($file_path);
$extension = '.' . $file_info['extension'];
// the image path without the extension
$no_ext_path = $file_info['dirname'] . '/' . $file_info['filename'];
$cropped_img_path = $no_ext_path . '-' . $width . 'x' . $height . $extension;
// checking if the file size is larger than the target size
// if it is smaller or the same size, stop right here and return
if ($image_src[1] > $width || $image_src[2] > $height) {
// the file is larger, check if the resized version already exists (for $crop = true but will also work for $crop = false if the sizes match)
if (file_exists($cropped_img_path)) {
$cropped_img_url = str_replace(basename($image_src[0]), basename($cropped_img_path), $image_src[0]);
$vt_image = array('url' => $cropped_img_url, 'width' => $width, 'height' => $height);
return $vt_image;
}
// $crop = false
if ($crop == false) {
// calculate the size proportionaly
$proportional_size = wp_constrain_dimensions($image_src[1], $image_src[2], $width, $height);
$resized_img_path = $no_ext_path . '-' . $proportional_size[0] . 'x' . $proportional_size[1] . $extension;
// checking if the file already exists
if (file_exists($resized_img_path)) {
$resized_img_url = str_replace(basename($image_src[0]), basename($resized_img_path), $image_src[0]);
$vt_image = array('url' => $resized_img_url, 'width' => $proportional_size[0], 'height' => $proportional_size[1]);
return $vt_image;
}
}
// no cache files - let's finally resize it
$new_img_path = image_resize($file_path, $width, $height, $crop);
$new_img_size = getimagesize($new_img_path);
$new_img = str_replace(basename($image_src[0]), basename($new_img_path), $image_src[0]);
// resized output
$vt_image = array('url' => $new_img, 'width' => $new_img_size[0], 'height' => $new_img_size[1]);
return $vt_image;
}
// default output - without resizing
$vt_image = array('url' => $image_src[0], 'width' => $image_src[1], 'height' => $image_src[2]);
return $vt_image;
}
示例6: hack_wp_generate_attachment_metadata
function hack_wp_generate_attachment_metadata($metadata, $attachment_id)
{
if (!isset($metadata['file'])) {
return $metadata;
}
$attachment = get_post($attachment_id);
$uploadPath = wp_upload_dir();
$file = path_join($uploadPath['basedir'], $metadata['file']);
$metadata = array();
if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) {
$imagesize = getimagesize($file);
$metadata['width'] = $imagesize[0];
$metadata['height'] = $imagesize[1];
list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96);
$metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
// Make the file path relative to the upload dir
$metadata['file'] = _wp_relative_upload_path($file);
// make thumbnails and other intermediate sizes
global $_wp_additional_image_sizes;
foreach (get_intermediate_image_sizes() as $s) {
$sizes[$s] = array('width' => '', 'height' => '', 'crop' => FALSE);
if (isset($_wp_additional_image_sizes[$s]['width'])) {
$sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']);
} else {
$sizes[$s]['width'] = get_option("{$s}_size_w");
}
// For default sizes set in options
if (isset($_wp_additional_image_sizes[$s]['height'])) {
$sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']);
} else {
$sizes[$s]['height'] = get_option("{$s}_size_h");
}
// For default sizes set in options
if (isset($_wp_additional_image_sizes[$s]['crop'])) {
$sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']);
} else {
$sizes[$s]['crop'] = get_option("{$s}_crop");
}
// For default sizes set in options
}
foreach ($sizes as $size => $size_data) {
$resized = hack_image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop'], $size);
if ($resized) {
$metadata['sizes'][$size] = $resized;
}
}
// fetch additional metadata from exif/iptc
$image_meta = wp_read_image_metadata($file);
if ($image_meta) {
$metadata['image_meta'] = $image_meta;
}
}
return $metadata;
}
示例7: test_constrain_dims_boundary
function test_constrain_dims_boundary()
{
if (!is_callable('wp_constrain_dimensions')) {
$this->markTestSkipped('wp_constrain_dimensions() is not callable.');
}
// one dimension is larger than the constraint, one smaller - result should be constrained
$out = wp_constrain_dimensions(1024, 768, 500, 800);
$this->assertSame(array(500, 375), $out);
$out = wp_constrain_dimensions(1024, 768, 2000, 700);
$this->assertSame(array(933, 700), $out);
// portrait
$out = wp_constrain_dimensions(768, 1024, 800, 500);
$this->assertSame(array(375, 500), $out);
$out = wp_constrain_dimensions(768, 1024, 2000, 700);
$this->assertSame(array(525, 700), $out);
}
示例8: ml_image_resize
function ml_image_resize($img_url, $width, $height, $crop = false, $jpeg_quality = 90)
{
$file_path = parse_url($img_url);
//$file_path = ltrim( $file_path['path'], '/' );
$file_path = rtrim(ABSPATH, '/') . $file_path['path'];
$orig_size = @getimagesize($file_path);
$image_src[0] = $img_url;
$image_src[1] = $orig_size[0];
$image_src[2] = $orig_size[1];
$file_info = pathinfo($file_path);
$extension = '.' . $file_info['extension'];
// the image path without the extension
$no_ext_path = $file_info['dirname'] . '/' . $file_info['filename'];
$cropped_img_path = $no_ext_path . '-' . $width . 'x' . $height . $extension;
// checking if the file size is larger than the target size
// if it is smaller or the same size, stop right here and return
if ($image_src[1] > $width || $image_src[2] > $height) {
// the file is larger, check if the resized version already exists (for crop = true but will also work for crop = false if the sizes match)
if (file_exists($cropped_img_path)) {
$cropped_img_url = str_replace(basename($image_src[0]), basename($cropped_img_path), $image_src[0]);
return $cropped_img_url;
}
// crop = false
if ($crop == false) {
// calculate the size proportionaly
$proportional_size = wp_constrain_dimensions($image_src[1], $image_src[2], $width, $height);
$resized_img_path = $no_ext_path . '-' . $proportional_size[0] . 'x' . $proportional_size[1] . $extension;
// checking if the file already exists
if (file_exists($resized_img_path)) {
$resized_img_url = str_replace(basename($image_src[0]), basename($resized_img_path), $image_src[0]);
return $resized_img_url;
}
}
// no cached files - let's finally resize it
$new_img_path = image_resize($file_path, $width, $height, $crop, NULL, $cropped_img_path, $jpeg_quality);
$new_img_size = @getimagesize($new_img_path);
$new_img = str_replace(basename($image_src[0]), basename($new_img_path), $image_src[0]);
// resized output
return $new_img;
}
return $image_src[0];
}
示例9: wp_generate_attachment_metadata_custom
/**
* Generate post thumbnail attachment meta data.
*
* @since 2.1.0
*
* @param int $attachment_id Attachment Id to process.
* @param string $file Filepath of the Attached image.
*
* @param null|array $thumbnails: thumbnails to regenerate, if null all
*
* @return mixed Metadata for attachment.
*/
public static function wp_generate_attachment_metadata_custom($attachment_id, $file, $thumbnails = null)
{
$attachment = get_post($attachment_id);
$meta_datas = get_post_meta($attachment_id, '_wp_attachment_metadata', true);
$metadata = array();
if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) {
$imagesize = getimagesize($file);
$metadata['width'] = $imagesize[0];
$metadata['height'] = $imagesize[1];
list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96);
$metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
// Make the file path relative to the upload dir
$metadata['file'] = _wp_relative_upload_path($file);
// make thumbnails and other intermediate sizes
global $_wp_additional_image_sizes;
foreach (get_intermediate_image_sizes() as $s) {
$sizes[$s] = array('width' => '', 'height' => '', 'crop' => false);
if (isset($_wp_additional_image_sizes[$s]['width'])) {
$sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']);
} else {
$sizes[$s]['width'] = get_option("{$s}_size_w");
}
// For default sizes set in options
if (isset($_wp_additional_image_sizes[$s]['height'])) {
$sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']);
} else {
$sizes[$s]['height'] = get_option("{$s}_size_h");
}
// For default sizes set in options
if (isset($_wp_additional_image_sizes[$s]['crop'])) {
$sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']);
} else {
$sizes[$s]['crop'] = get_option("{$s}_crop");
}
// For default sizes set in options
}
$sizes = apply_filters('intermediate_image_sizes_advanced', $sizes);
// Only if not all sizes
if (isset($thumbnails) && is_array($thumbnails) && isset($meta_datas['sizes']) && !empty($meta_datas['sizes'])) {
// Fill the array with the other sizes not have to be done
foreach ($meta_datas['sizes'] as $name => $fsize) {
$metadata['sizes'][$name] = $fsize;
}
}
foreach ($sizes as $size => $size_data) {
if (isset($thumbnails)) {
if (!in_array($size, $thumbnails)) {
continue;
}
}
$resized = image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']);
if (isset($meta_datas['size'][$size])) {
// Remove the size from the orignal sizes for after work
unset($meta_datas['size'][$size]);
}
if ($resized) {
$metadata['sizes'][$size] = $resized;
}
}
// fetch additional metadata from exif/iptc
$image_meta = wp_read_image_metadata($file);
if ($image_meta) {
$metadata['image_meta'] = $image_meta;
}
}
return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id);
}
示例10: wp_image_editor
//.........这里部分代码省略.........
, 1, this)" style="width:3em;" />
</span>
</p>
<p id="imgedit-crop-sel-<?php
echo $post_id;
?>
">
<?php
_e('Selection:');
?>
<span class="nowrap">
<input type="text" id="imgedit-sel-width-<?php
echo $post_id;
?>
" onkeyup="imageEdit.setNumSelection(<?php
echo $post_id;
?>
)" style="width:4em;" />
×
<input type="text" id="imgedit-sel-height-<?php
echo $post_id;
?>
" onkeyup="imageEdit.setNumSelection(<?php
echo $post_id;
?>
)" style="width:4em;" />
</span>
</p>
</div>
<?php
if ($thumb && $sub_sizes) {
$thumb_img = wp_constrain_dimensions($thumb['width'], $thumb['height'], 160, 120);
?>
<div class="imgedit-group imgedit-applyto">
<div class="imgedit-group-top">
<h3><?php
_e('Thumbnail Settings');
?>
<a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
<p class="imgedit-help"><?php
_e('You can edit the image while preserving the thumbnail. For example, you may wish to have a square thumbnail that displays just a section of the image.');
?>
</p>
</div>
<p>
<img src="<?php
echo $thumb['url'];
?>
" width="<?php
echo $thumb_img[0];
?>
" height="<?php
echo $thumb_img[1];
?>
" class="imgedit-size-preview" alt="" draggable="false" />
<br /><?php
_e('Current thumbnail');
?>
</p>
<p id="imgedit-save-target-<?php
echo $post_id;
示例11: filter_srcset_array
/**
* Filters an array of image `srcset` values, replacing each URL with its Photon equivalent.
*
* @since 3.8.0
* @since 4.0.4 Added automatically additional sizes beyond declared image sizes.
* @param array $sources An array of image urls and widths.
* @uses self::validate_image_url, jetpack_photon_url, Jetpack_Photon::parse_from_filename
* @uses Jetpack_Photon::strip_image_dimensions_maybe, Jetpack::get_content_width
* @return array An array of Photon image urls and widths.
*/
public function filter_srcset_array($sources, $size_array, $image_src, $image_meta)
{
$upload_dir = wp_upload_dir();
foreach ($sources as $i => $source) {
if (!self::validate_image_url($source['url'])) {
continue;
}
/** This filter is already documented in class.photon.php */
if (apply_filters('jetpack_photon_skip_image', false, $source['url'], $source)) {
continue;
}
$url = $source['url'];
list($width, $height) = Jetpack_Photon::parse_dimensions_from_filename($url);
// It's quicker to get the full size with the data we have already, if available
if (isset($image_meta['file'])) {
$url = trailingslashit($upload_dir['baseurl']) . $image_meta['file'];
} else {
$url = Jetpack_Photon::strip_image_dimensions_maybe($url);
}
$args = array();
if ('w' === $source['descriptor']) {
if ($height && $source['value'] == $width) {
$args['resize'] = $width . ',' . $height;
} else {
$args['w'] = $source['value'];
}
}
$sources[$i]['url'] = jetpack_photon_url($url, $args);
}
/**
* At this point, $sources is the original srcset with Photonized URLs.
* Now, we're going to construct additional sizes based on multiples of the content_width.
* This will reduce the gap between the largest defined size and the original image.
*/
/**
* Filter the multiplier Photon uses to create new srcset items.
* Return false to short-circuit and bypass auto-generation.
*
* @module photon
*
* @since 4.0.4
*
* @param array|bool $multipliers Array of multipliers to use or false to bypass.
*/
$multipliers = apply_filters('jetpack_photon_srcset_multipliers', array(2, 3));
$url = trailingslashit($upload_dir['baseurl']) . $image_meta['file'];
if (is_array($multipliers) && !apply_filters('jetpack_photon_skip_image', false, $url, null) && isset($image_meta['width']) && isset($image_meta['height']) && isset($image_meta['file']) && isset($size_array[0]) && isset($size_array[1])) {
$fullwidth = $image_meta['width'];
$fullheight = $image_meta['height'];
$reqwidth = $size_array[0];
$reqheight = $size_array[1];
$constrained_size = wp_constrain_dimensions($fullwidth, $fullheight, $reqwidth);
$expected_size = array($reqwidth, $reqheight);
if (abs($constrained_size[0] - $expected_size[0]) <= 1 && abs($constrained_size[1] - $expected_size[1]) <= 1) {
$crop = 'soft';
$base = Jetpack::get_content_width() ? Jetpack::get_content_width() : 1000;
// Provide a default width if none set by the theme.
} else {
$crop = 'hard';
$base = $reqwidth;
}
$currentwidths = array_keys($sources);
$newsources = null;
foreach ($multipliers as $multiplier) {
$newwidth = $base * $multiplier;
foreach ($currentwidths as $currentwidth) {
// If a new width would be within 100 pixes of an existing one or larger than the full size image, skip.
if (abs($currentwidth - $newwidth) < 50 || $newwidth > $fullwidth) {
continue 2;
// Back to the foreach ( $multipliers as $multiplier )
}
}
// foreach ( $currentwidths as $currentwidth ){
if ('soft' == $crop) {
$args = array('w' => $newwidth);
} else {
// hard crop, e.g. add_image_size( 'example', 200, 200, true );
$args = array('zoom' => $multiplier, 'resize' => $reqwidth . ',' . $reqheight);
}
$newsources[$newwidth] = array('url' => jetpack_photon_url($url, $args), 'descriptor' => 'w', 'value' => $newwidth);
}
// foreach ( $multipliers as $multiplier )
if (is_array($newsources)) {
$sources = array_merge($sources, $newsources);
}
}
// if ( isset( $image_meta['width'] ) && isset( $image_meta['file'] ) )
return $sources;
}
示例12: wp_save_image
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();
//.........这里部分代码省略.........
示例13: new_image_resize_dimensions
function new_image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false)
{
if ($orig_w <= 0 || $orig_h <= 0) {
return false;
}
// at least one of dest_w or dest_h must be specific
if ($dest_w <= 0 && $dest_h <= 0) {
return false;
}
if ($crop) {
// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
$aspect_ratio = $orig_w / $orig_h;
$new_w = $dest_w;
$new_h = $dest_h;
if (!$new_w) {
$new_w = intval($new_h * $aspect_ratio);
}
if (!$new_h) {
$new_h = intval($new_w / $aspect_ratio);
}
$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
$crop_w = round($new_w / $size_ratio);
$crop_h = round($new_h / $size_ratio);
$s_x = floor(($orig_w - $crop_w) / 2);
$s_y = floor(($orig_h - $crop_h) / 2);
} else {
// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
$crop_w = $orig_w;
$crop_h = $orig_h;
$s_x = 0;
$s_y = 0;
list($new_w, $new_h) = wp_constrain_dimensions($orig_w, $orig_h, $dest_w, $dest_h);
}
// the return array matches the parameters to imagecopyresampled()
// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
return array(0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h);
}
示例14: cached_singlepic_file
/**
* This function creates a cache for all singlepics to reduce the CPU load
*
* @param int $width
* @param int $height
* @param string $mode could be watermark | web20 | crop
* @return the url for the image or false if failed
*/
function cached_singlepic_file($width = '', $height = '', $mode = '')
{
$ngg_options = get_option('ngg_options');
include_once nggGallery::graphic_library();
// cache filename should be unique
$cachename = $this->pid . '_' . $mode . '_' . $width . 'x' . $height . '_' . $this->filename;
$cachefolder = WINABSPATH . $ngg_options['gallerypath'] . 'cache/';
$cached_url = site_url() . '/' . $ngg_options['gallerypath'] . 'cache/' . $cachename;
$cached_file = $cachefolder . $cachename;
// check first for the file
if (file_exists($cached_file)) {
return $cached_url;
}
// create folder if needed
if (!file_exists($cachefolder)) {
if (!wp_mkdir_p($cachefolder)) {
return false;
}
}
$thumb = new ngg_Thumbnail($this->imagePath, TRUE);
// echo $thumb->errmsg;
if (!$thumb->error) {
if ($mode == 'crop') {
// calculates the new dimentions for a downsampled image
list($ratio_w, $ratio_h) = wp_constrain_dimensions($thumb->currentDimensions['width'], $thumb->currentDimensions['height'], $width, $height);
// check ratio to decide which side should be resized
$ratio_h < $height || $ratio_w == $width ? $thumb->resize(0, $height) : $thumb->resize($width, 0);
// get the best start postion to crop from the middle
$ypos = ($thumb->currentDimensions['height'] - $height) / 2;
$thumb->crop(0, $ypos, $width, $height);
} else {
$thumb->resize($width, $height);
}
if ($mode == 'watermark') {
if ($ngg_options['wmType'] == 'image') {
$thumb->watermarkImgPath = $ngg_options['wmPath'];
$thumb->watermarkImage($ngg_options['wmPos'], $ngg_options['wmXpos'], $ngg_options['wmYpos']);
}
if ($ngg_options['wmType'] == 'text') {
$thumb->watermarkText = $ngg_options['wmText'];
$thumb->watermarkCreateText($ngg_options['wmColor'], $ngg_options['wmFont'], $ngg_options['wmSize'], $ngg_options['wmOpaque']);
$thumb->watermarkImage($ngg_options['wmPos'], $ngg_options['wmXpos'], $ngg_options['wmYpos']);
}
}
if ($mode == 'web20') {
$thumb->createReflection(40, 40, 50, false, '#a4a4a4');
}
// save the new cache picture
$thumb->save($cached_file, $ngg_options['imgQuality']);
}
$thumb->destruct();
// check again for the file
if (file_exists($cached_file)) {
return $cached_url;
}
return false;
}
示例15: vt_resize
function vt_resize($attach_id = null, $img_url = null, $width, $height, $crop = false)
{
// Cast $width and $height to integer
$width = intval($width);
$height = intval($height);
// this is an attachment, so we have the ID
if ($attach_id) {
$image_src = wp_get_attachment_image_src($attach_id, 'full');
$file_path = get_attached_file($attach_id);
// this is not an attachment, let's use the image url
} else {
if ($img_url) {
$file_path = parse_url(esc_url($img_url));
$file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path['path'];
//$file_path = ltrim( $file_path['path'], '/' );
//$file_path = rtrim( ABSPATH, '/' ).$file_path['path'];
$orig_size = getimagesize($file_path);
$image_src[0] = $img_url;
$image_src[1] = $orig_size[0];
$image_src[2] = $orig_size[1];
}
}
$file_info = pathinfo($file_path);
// check if file exists
if (!isset($file_info['dirname']) && !isset($file_info['filename']) && !isset($file_info['extension'])) {
return;
}
$base_file = $file_info['dirname'] . '/' . $file_info['filename'] . '.' . $file_info['extension'];
if (!file_exists($base_file)) {
return;
}
$extension = '.' . $file_info['extension'];
// the image path without the extension
$no_ext_path = $file_info['dirname'] . '/' . $file_info['filename'];
$cropped_img_path = $no_ext_path . '-' . $width . 'x' . $height . $extension;
// checking if the file size is larger than the target size
// if it is smaller or the same size, stop right here and return
if ($image_src[1] > $width) {
// the file is larger, check if the resized version already exists (for $crop = true but will also work for $crop = false if the sizes match)
if (file_exists($cropped_img_path)) {
$cropped_img_url = str_replace(basename($image_src[0]), basename($cropped_img_path), $image_src[0]);
$vt_image = array('url' => $cropped_img_url, 'width' => $width, 'height' => $height);
return $vt_image;
}
// $crop = false or no height set
if ($crop == false or !$height) {
// calculate the size proportionaly
$proportional_size = wp_constrain_dimensions($image_src[1], $image_src[2], $width, $height);
$resized_img_path = $no_ext_path . '-' . $proportional_size[0] . 'x' . $proportional_size[1] . $extension;
// checking if the file already exists
if (file_exists($resized_img_path)) {
$resized_img_url = str_replace(basename($image_src[0]), basename($resized_img_path), $image_src[0]);
$vt_image = array('url' => $resized_img_url, 'width' => $proportional_size[0], 'height' => $proportional_size[1]);
return $vt_image;
}
}
// check if image width is smaller than set width
$img_size = getimagesize($file_path);
if ($img_size[0] <= $width) {
$width = $img_size[0];
}
// Check if GD Library installed
if (!function_exists('imagecreatetruecolor')) {
echo 'GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library';
return;
}
// no cache files - let's finally resize it
if (function_exists('wp_get_image_editor')) {
$image = wp_get_image_editor($file_path);
if (!is_wp_error($image)) {
$image->resize($width, $height, $crop);
$save_data = $image->save();
if (isset($save_data['path'])) {
$new_img_path = $save_data['path'];
}
}
} else {
$new_img_path = image_resize($file_path, $width, $height, $crop);
}
$new_img_size = getimagesize($new_img_path);
$new_img = str_replace(basename($image_src[0]), basename($new_img_path), $image_src[0]);
// resized output
$vt_image = array('url' => $new_img, 'width' => $new_img_size[0], 'height' => $new_img_size[1]);
return $vt_image;
}
// default output - without resizing
$vt_image = array('url' => $image_src[0], 'width' => $width, 'height' => $height);
return $vt_image;
}