3 * WordPress Image Editor
6 * @subpackage Administration
9 function wp_image_editor($post_id, $msg = false) {
10 $nonce = wp_create_nonce("image_editor-$post_id");
11 $meta = wp_get_attachment_metadata($post_id);
12 $thumb = image_get_intermediate_size($post_id, 'thumbnail');
13 $sub_sizes = isset($meta['sizes']) && is_array($meta['sizes']);
16 if ( isset( $meta['width'], $meta['height'] ) )
17 $big = max( $meta['width'], $meta['height'] );
19 die( __('Image data does not exist. Please re-upload the image.') );
21 $sizer = $big > 400 ? 400 / $big : 1;
23 $backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
25 if ( ! empty( $backup_sizes ) && isset( $backup_sizes['full-orig'], $meta['file'] ) )
26 $can_restore = $backup_sizes['full-orig']['file'] != basename( $meta['file'] );
29 if ( isset($msg->error) )
30 $note = "<div class='error'><p>$msg->error</p></div>";
31 elseif ( isset($msg->msg) )
32 $note = "<div class='updated'><p>$msg->msg</p></div>";
36 <div class="imgedit-wrap">
37 <div id="imgedit-panel-<?php echo $post_id; ?>">
39 <div class="imgedit-settings">
40 <div class="imgedit-group">
41 <div class="imgedit-group-top">
42 <h3><?php _e( 'Scale Image' ); ?> <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
43 <div class="imgedit-help">
44 <p><?php _e('You can proportionally scale the original image. For best results, scaling should be done before you crop, flip, or rotate. Images can only be scaled down, not up.'); ?></p>
46 <?php if ( isset( $meta['width'], $meta['height'] ) ): ?>
47 <p><?php printf( __('Original dimensions %s'), $meta['width'] . ' × ' . $meta['height'] ); ?></p>
49 <div class="imgedit-submit">
50 <span class="nowrap"><input type="text" id="imgedit-scale-width-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1)" style="width:4em;" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" /> × <input type="text" id="imgedit-scale-height-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0)" style="width:4em;" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
51 <span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php echo $post_id; ?>">!</span></span>
52 <input type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'scale')" class="button button-primary" value="<?php esc_attr_e( 'Scale' ); ?>" />
57 <?php if ( $can_restore ) { ?>
59 <div class="imgedit-group">
60 <div class="imgedit-group-top">
61 <h3><a onclick="imageEdit.toggleHelp(this);return false;" href="#"><?php _e('Restore Original Image'); ?> <span class="dashicons dashicons-arrow-down imgedit-help-toggle"></span></a></h3>
62 <div class="imgedit-help">
63 <p><?php _e('Discard any changes and restore the original image.');
65 if ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE )
66 echo ' '.__('Previously edited copies of the image will not be deleted.');
69 <div class="imgedit-submit">
70 <input type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'restore')" class="button button-primary" value="<?php esc_attr_e( 'Restore image' ); ?>" <?php echo $can_restore; ?> />
78 <div class="imgedit-group">
79 <div class="imgedit-group-top">
80 <h3><?php _e('Image Crop'); ?> <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
82 <div class="imgedit-help">
83 <p><?php _e('To crop the image, click on it and drag to make your selection.'); ?></p>
85 <p><strong><?php _e('Crop Aspect Ratio'); ?></strong><br />
86 <?php _e('The aspect ratio is the relationship between the width and height. You can preserve the aspect ratio by holding down the shift key while resizing your selection. Use the input box to specify the aspect ratio, e.g. 1:1 (square), 4:3, 16:9, etc.'); ?></p>
88 <p><strong><?php _e('Crop Selection'); ?></strong><br />
89 <?php _e('Once you have made your selection, you can adjust it by entering the size in pixels. The minimum selection size is the thumbnail size as set in the Media settings.'); ?></p>
94 <?php _e('Aspect ratio:'); ?>
96 <input type="text" id="imgedit-crop-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" style="width:3em;" />
98 <input type="text" id="imgedit-crop-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" style="width:3em;" />
102 <p id="imgedit-crop-sel-<?php echo $post_id; ?>">
103 <?php _e('Selection:'); ?>
104 <span class="nowrap">
105 <input type="text" id="imgedit-sel-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" style="width:4em;" />
107 <input type="text" id="imgedit-sel-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" style="width:4em;" />
112 <?php if ( $thumb && $sub_sizes ) {
113 $thumb_img = wp_constrain_dimensions( $thumb['width'], $thumb['height'], 160, 120 );
116 <div class="imgedit-group imgedit-applyto">
117 <div class="imgedit-group-top">
118 <h3><?php _e('Thumbnail Settings'); ?> <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
119 <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>
123 <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" />
124 <br /><?php _e('Current thumbnail'); ?>
127 <p id="imgedit-save-target-<?php echo $post_id; ?>">
128 <strong><?php _e('Apply changes to:'); ?></strong><br />
130 <label class="imgedit-label">
131 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="all" checked="checked" />
132 <?php _e('All image sizes'); ?></label>
134 <label class="imgedit-label">
135 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="thumbnail" />
136 <?php _e('Thumbnail'); ?></label>
138 <label class="imgedit-label">
139 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="nothumb" />
140 <?php _e('All sizes except thumbnail'); ?></label>
148 <div class="imgedit-panel-content">
150 <div class="imgedit-menu">
151 <div onclick="imageEdit.crop(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-crop disabled" title="<?php esc_attr_e( 'Crop' ); ?>"></div><?php
153 // On some setups GD library does not provide imagerotate() - Ticket #11536
154 if ( wp_image_editor_supports( array( 'mime_type' => get_post_mime_type( $post_id ), 'methods' => array( 'rotate' ) ) ) ) { ?>
155 <div class="imgedit-rleft" onclick="imageEdit.rotate( 90, <?php echo "$post_id, '$nonce'"; ?>, this)" title="<?php esc_attr_e( 'Rotate counter-clockwise' ); ?>"></div>
156 <div class="imgedit-rright" onclick="imageEdit.rotate(-90, <?php echo "$post_id, '$nonce'"; ?>, this)" title="<?php esc_attr_e( 'Rotate clockwise' ); ?>"></div>
158 $note_no_rotate = esc_attr__('Image rotation is not supported by your web host.');
160 <div class="imgedit-rleft disabled" title="<?php echo $note_no_rotate; ?>"></div>
161 <div class="imgedit-rright disabled" title="<?php echo $note_no_rotate; ?>"></div>
164 <div onclick="imageEdit.flip(1, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-flipv" title="<?php esc_attr_e( 'Flip vertically' ); ?>"></div>
165 <div onclick="imageEdit.flip(2, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-fliph" title="<?php esc_attr_e( 'Flip horizontally' ); ?>"></div>
167 <div id="image-undo-<?php echo $post_id; ?>" onclick="imageEdit.undo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-undo disabled" title="<?php esc_attr_e( 'Undo' ); ?>"></div>
168 <div id="image-redo-<?php echo $post_id; ?>" onclick="imageEdit.redo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-redo disabled" title="<?php esc_attr_e( 'Redo' ); ?>"></div>
172 <input type="hidden" id="imgedit-sizer-<?php echo $post_id; ?>" value="<?php echo $sizer; ?>" />
173 <input type="hidden" id="imgedit-history-<?php echo $post_id; ?>" value="" />
174 <input type="hidden" id="imgedit-undone-<?php echo $post_id; ?>" value="0" />
175 <input type="hidden" id="imgedit-selection-<?php echo $post_id; ?>" value="" />
176 <input type="hidden" id="imgedit-x-<?php echo $post_id; ?>" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
177 <input type="hidden" id="imgedit-y-<?php echo $post_id; ?>" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
179 <div id="imgedit-crop-<?php echo $post_id; ?>" class="imgedit-crop-wrap">
180 <img id="image-preview-<?php echo $post_id; ?>" onload="imageEdit.imgLoaded('<?php echo $post_id; ?>')" src="<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>?action=imgedit-preview&_ajax_nonce=<?php echo $nonce; ?>&postid=<?php echo $post_id; ?>&rand=<?php echo rand(1, 99999); ?>" />
183 <div class="imgedit-submit">
184 <input type="button" onclick="imageEdit.close(<?php echo $post_id; ?>, 1)" class="button" value="<?php esc_attr_e( 'Cancel' ); ?>" />
185 <input type="button" onclick="imageEdit.save(<?php echo "$post_id, '$nonce'"; ?>)" disabled="disabled" class="button button-primary imgedit-submit-btn" value="<?php esc_attr_e( 'Save' ); ?>" />
190 <div class="imgedit-wait" id="imgedit-wait-<?php echo $post_id; ?>"></div>
191 <script type="text/javascript">jQuery( function() { imageEdit.init(<?php echo $post_id; ?>); });</script>
192 <div class="hidden" id="imgedit-leaving-<?php echo $post_id; ?>"><?php _e("There are unsaved changes that will be lost. 'OK' to continue, 'Cancel' to return to the Image Editor."); ?></div>
198 * Streams image in WP_Image_Editor to browser.
199 * Provided for backcompat reasons
201 * @param WP_Image_Editor $image
202 * @param string $mime_type
203 * @param int $post_id
206 function wp_stream_image( $image, $mime_type, $post_id ) {
207 if ( $image instanceof WP_Image_Editor ) {
210 * Filter the WP_Image_Editor instance for the image to be streamed to the browser.
214 * @param WP_Image_Editor $image WP_Image_Editor instance.
215 * @param int $post_id Post ID.
217 $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
219 if ( is_wp_error( $image->stream( $mime_type ) ) )
224 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
227 * Filter the GD image resource to be streamed to the browser.
230 * @deprecated 3.5.0 Use image_editor_save_pre instead.
232 * @param resource $image Image resource to be streamed.
233 * @param int $post_id Post ID.
235 $image = apply_filters( 'image_save_pre', $image, $post_id );
237 switch ( $mime_type ) {
239 header( 'Content-Type: image/jpeg' );
240 return imagejpeg( $image, null, 90 );
242 header( 'Content-Type: image/png' );
243 return imagepng( $image );
245 header( 'Content-Type: image/gif' );
246 return imagegif( $image );
254 * Saves Image to File
256 * @param string $filename
257 * @param WP_Image_Editor $image
258 * @param string $mime_type
259 * @param int $post_id
262 function wp_save_image_file( $filename, $image, $mime_type, $post_id ) {
263 if ( $image instanceof WP_Image_Editor ) {
265 /** This filter is documented in wp-admin/includes/image-edit.php */
266 $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
269 * Filter whether to skip saving the image file.
271 * Returning a non-null value will short-circuit the save method,
272 * returning that value instead.
276 * @param mixed $override Value to return instead of saving. Default null.
277 * @param string $filename Name of the file to be saved.
278 * @param WP_Image_Editor $image WP_Image_Editor instance.
279 * @param string $mime_type Image mime type.
280 * @param int $post_id Post ID.
282 $saved = apply_filters( 'wp_save_image_editor_file', null, $filename, $image, $mime_type, $post_id );
284 if ( null !== $saved )
287 return $image->save( $filename, $mime_type );
289 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
291 /** This filter is documented in wp-admin/includes/image-edit.php */
292 $image = apply_filters( 'image_save_pre', $image, $post_id );
295 * Filter whether to skip saving the image file.
297 * Returning a non-null value will short-circuit the save method,
298 * returning that value instead.
301 * @deprecated 3.5.0 Use wp_save_image_editor_file instead.
303 * @param mixed $override Value to return instead of saving. Default null.
304 * @param string $filename Name of the file to be saved.
305 * @param WP_Image_Editor $image WP_Image_Editor instance.
306 * @param string $mime_type Image mime type.
307 * @param int $post_id Post ID.
309 $saved = apply_filters( 'wp_save_image_file', null, $filename, $image, $mime_type, $post_id );
311 if ( null !== $saved )
314 switch ( $mime_type ) {
317 /** This filter is documented in wp-includes/class-wp-image-editor.php */
318 return imagejpeg( $image, $filename, apply_filters( 'jpeg_quality', 90, 'edit_image' ) );
320 return imagepng( $image, $filename );
322 return imagegif( $image, $filename );
329 function _image_get_preview_ratio($w, $h) {
331 return $max > 400 ? (400 / $max) : 1;
334 // @TODO: Returns GD resource, but is NOT public
335 function _rotate_image_resource($img, $angle) {
336 _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::rotate' ) );
337 if ( function_exists('imagerotate') ) {
338 $rotated = imagerotate($img, $angle, 0);
339 if ( is_resource($rotated) ) {
348 * @TODO: Only used within image_edit_apply_changes
349 * and receives/returns GD Resource.
352 * @param GD_Resource $img
353 * @param boolean $horz
354 * @param boolean $vert
355 * @return GD_Resource
357 function _flip_image_resource($img, $horz, $vert) {
358 _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::flip' ) );
361 $dst = wp_imagecreatetruecolor($w, $h);
362 if ( is_resource($dst) ) {
363 $sx = $vert ? ($w - 1) : 0;
364 $sy = $horz ? ($h - 1) : 0;
365 $sw = $vert ? -$w : $w;
366 $sh = $horz ? -$h : $h;
368 if ( imagecopyresampled($dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh) ) {
377 * @TODO: Only used within image_edit_apply_changes
378 * and receives/returns GD Resource.
381 * @param GD_Resource $img
386 * @return GD_Resource
388 function _crop_image_resource($img, $x, $y, $w, $h) {
389 $dst = wp_imagecreatetruecolor($w, $h);
390 if ( is_resource($dst) ) {
391 if ( imagecopy($dst, $img, 0, 0, $x, $y, $w, $h) ) {
400 * Performs group of changes on Editor specified.
402 * @param WP_Image_Editor $image
403 * @param type $changes
404 * @return WP_Image_Editor
406 function image_edit_apply_changes( $image, $changes ) {
407 if ( is_resource( $image ) )
408 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
410 if ( !is_array($changes) )
413 // Expand change operations.
414 foreach ( $changes as $key => $obj ) {
415 if ( isset($obj->r) ) {
416 $obj->type = 'rotate';
417 $obj->angle = $obj->r;
419 } elseif ( isset($obj->f) ) {
421 $obj->axis = $obj->f;
423 } elseif ( isset($obj->c) ) {
428 $changes[$key] = $obj;
431 // Combine operations.
432 if ( count($changes) > 1 ) {
433 $filtered = array($changes[0]);
434 for ( $i = 0, $j = 1; $j < count($changes); $j++ ) {
436 if ( $filtered[$i]->type == $changes[$j]->type ) {
437 switch ( $filtered[$i]->type ) {
439 $filtered[$i]->angle += $changes[$j]->angle;
443 $filtered[$i]->axis ^= $changes[$j]->axis;
449 $filtered[++$i] = $changes[$j];
451 $changes = $filtered;
455 // Image resource before applying the changes.
456 if ( $image instanceof WP_Image_Editor ) {
459 * Filter the WP_Image_Editor instance before applying changes to the image.
463 * @param WP_Image_Editor $image WP_Image_Editor instance.
464 * @param array $changes Array of change operations.
466 $image = apply_filters( 'wp_image_editor_before_change', $image, $changes );
467 } elseif ( is_resource( $image ) ) {
470 * Filter the GD image resource before applying changes to the image.
473 * @deprecated 3.5.0 Use wp_image_editor_before_change instead.
475 * @param resource $image GD image resource.
476 * @param array $changes Array of change operations.
478 $image = apply_filters( 'image_edit_before_change', $image, $changes );
481 foreach ( $changes as $operation ) {
482 switch ( $operation->type ) {
484 if ( $operation->angle != 0 ) {
485 if ( $image instanceof WP_Image_Editor )
486 $image->rotate( $operation->angle );
488 $image = _rotate_image_resource( $image, $operation->angle );
492 if ( $operation->axis != 0 )
493 if ( $image instanceof WP_Image_Editor )
494 $image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 );
496 $image = _flip_image_resource( $image, ( $operation->axis & 1 ) != 0, ( $operation->axis & 2 ) != 0 );
499 $sel = $operation->sel;
501 if ( $image instanceof WP_Image_Editor ) {
502 $size = $image->get_size();
504 $h = $size['height'];
506 $scale = 1 / _image_get_preview_ratio( $w, $h ); // discard preview scaling
507 $image->crop( $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
509 $scale = 1 / _image_get_preview_ratio( imagesx( $image ), imagesy( $image ) ); // discard preview scaling
510 $image = _crop_image_resource( $image, $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
521 * Streams image in post to browser, along with enqueued changes
522 * in $_REQUEST['history']
524 * @param int $post_id
527 function stream_preview_image( $post_id ) {
528 $post = get_post( $post_id );
530 /** This filter is documented in wp-admin/admin.php */
531 @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
533 $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) );
535 if ( is_wp_error( $img ) )
538 $changes = !empty($_REQUEST['history']) ? json_decode( wp_unslash($_REQUEST['history']) ) : null;
540 $img = image_edit_apply_changes( $img, $changes );
543 $size = $img->get_size();
545 $h = $size['height'];
547 $ratio = _image_get_preview_ratio( $w, $h );
548 $w2 = max ( 1, $w * $ratio );
549 $h2 = max ( 1, $h * $ratio );
551 if ( is_wp_error( $img->resize( $w2, $h2 ) ) )
554 return wp_stream_image( $img, $post->post_mime_type, $post_id );
557 function wp_restore_image($post_id) {
558 $meta = wp_get_attachment_metadata($post_id);
559 $file = get_attached_file($post_id);
560 $backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
564 if ( !is_array($backup_sizes) ) {
565 $msg->error = __('Cannot load image metadata.');
569 $parts = pathinfo($file);
570 $suffix = time() . rand(100, 999);
571 $default_sizes = get_intermediate_image_sizes();
573 if ( isset($backup_sizes['full-orig']) && is_array($backup_sizes['full-orig']) ) {
574 $data = $backup_sizes['full-orig'];
576 if ( $parts['basename'] != $data['file'] ) {
577 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
579 // Delete only if it's edited image.
580 if ( preg_match('/-e[0-9]{13}\./', $parts['basename']) ) {
582 /** This filter is documented in wp-admin/custom-header.php */
583 $delpath = apply_filters( 'wp_delete_file', $file );
586 } elseif ( isset( $meta['width'], $meta['height'] ) ) {
587 $backup_sizes["full-$suffix"] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $parts['basename']);
591 $restored_file = path_join($parts['dirname'], $data['file']);
592 $restored = update_attached_file($post_id, $restored_file);
594 $meta['file'] = _wp_relative_upload_path( $restored_file );
595 $meta['width'] = $data['width'];
596 $meta['height'] = $data['height'];
599 foreach ( $default_sizes as $default_size ) {
600 if ( isset($backup_sizes["$default_size-orig"]) ) {
601 $data = $backup_sizes["$default_size-orig"];
602 if ( isset($meta['sizes'][$default_size]) && $meta['sizes'][$default_size]['file'] != $data['file'] ) {
603 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
605 // Delete only if it's edited image
606 if ( preg_match('/-e[0-9]{13}-/', $meta['sizes'][$default_size]['file']) ) {
607 /** This filter is documented in wp-admin/custom-header.php */
608 $delpath = apply_filters( 'wp_delete_file', path_join($parts['dirname'], $meta['sizes'][$default_size]['file']) );
612 $backup_sizes["$default_size-{$suffix}"] = $meta['sizes'][$default_size];
616 $meta['sizes'][$default_size] = $data;
618 unset($meta['sizes'][$default_size]);
622 if ( !wp_update_attachment_metadata($post_id, $meta) || !update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes) ) {
623 $msg->error = __('Cannot save image metadata.');
628 $msg->error = __('Image metadata is inconsistent.');
630 $msg->msg = __('Image restored successfully.');
636 * Saves image to post along with enqueued changes
637 * in $_REQUEST['history']
639 * @param int $post_id
642 function wp_save_image( $post_id ) {
643 global $_wp_additional_image_sizes;
645 $return = new stdClass;
646 $success = $delete = $scaled = $nocrop = false;
647 $post = get_post( $post_id );
649 $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) );
650 if ( is_wp_error( $img ) ) {
651 $return->error = esc_js( __('Unable to create new image.') );
655 $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
656 $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
657 $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
658 $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
660 if ( $scale && $fwidth > 0 && $fheight > 0 ) {
661 $size = $img->get_size();
662 $sX = $size['width'];
663 $sY = $size['height'];
665 // Check if it has roughly the same w / h ratio.
666 $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
667 if ( -0.1 < $diff && $diff < 0.1 ) {
668 // Scale the full size image.
669 if ( $img->resize( $fwidth, $fheight ) )
674 $return->error = esc_js( __('Error while saving the scaled image. Please reload the page and try again.') );
677 } elseif ( !empty($_REQUEST['history']) ) {
678 $changes = json_decode( wp_unslash($_REQUEST['history']) );
680 $img = image_edit_apply_changes($img, $changes);
682 $return->error = esc_js( __('Nothing to save, the image has not changed.') );
686 $meta = wp_get_attachment_metadata($post_id);
687 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
689 if ( !is_array($meta) ) {
690 $return->error = esc_js( __('Image data does not exist. Please re-upload the image.') );
694 if ( !is_array($backup_sizes) )
695 $backup_sizes = array();
697 // Generate new filename.
698 $path = get_attached_file($post_id);
699 $path_parts = pathinfo( $path );
700 $filename = $path_parts['filename'];
701 $suffix = time() . rand(100, 999);
703 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE &&
704 isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] ) {
706 if ( 'thumbnail' == $target )
707 $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}";
712 $filename = preg_replace( '/-e([0-9]+)$/', '', $filename );
713 $filename .= "-e{$suffix}";
714 $new_filename = "{$filename}.{$path_parts['extension']}";
715 $new_path = "{$path_parts['dirname']}/$new_filename";
716 if ( file_exists($new_path) )
723 // Save the full-size file, also needed to create sub-sizes.
724 if ( !wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id) ) {
725 $return->error = esc_js( __('Unable to save the image.') );
729 if ( 'nothumb' == $target || 'all' == $target || 'full' == $target || $scaled ) {
731 if ( isset($backup_sizes['full-orig']) ) {
732 if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] )
733 $tag = "full-$suffix";
739 $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']);
741 $success = update_attached_file( $post_id, $new_path );
743 $meta['file'] = _wp_relative_upload_path( $new_path );
745 $size = $img->get_size();
746 $meta['width'] = $size['width'];
747 $meta['height'] = $size['height'];
749 if ( $success && ('nothumb' == $target || 'all' == $target) ) {
750 $sizes = get_intermediate_image_sizes();
751 if ( 'nothumb' == $target )
752 $sizes = array_diff( $sizes, array('thumbnail') );
755 $return->fw = $meta['width'];
756 $return->fh = $meta['height'];
757 } elseif ( 'thumbnail' == $target ) {
758 $sizes = array( 'thumbnail' );
759 $success = $delete = $nocrop = true;
762 if ( isset( $sizes ) ) {
765 foreach ( $sizes as $size ) {
767 if ( isset( $meta['sizes'][$size] ) ) {
768 if ( isset($backup_sizes["$size-orig"]) ) {
769 if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes["$size-orig"]['file'] != $meta['sizes'][$size]['file'] )
770 $tag = "$size-$suffix";
776 $backup_sizes[$tag] = $meta['sizes'][$size];
779 if ( isset( $_wp_additional_image_sizes[ $size ] ) ) {
780 $width = intval( $_wp_additional_image_sizes[ $size ]['width'] );
781 $height = intval( $_wp_additional_image_sizes[ $size ]['height'] );
782 $crop = ( $nocrop ) ? false : $_wp_additional_image_sizes[ $size ]['crop'];
784 $height = get_option( "{$size}_size_h" );
785 $width = get_option( "{$size}_size_w" );
786 $crop = ( $nocrop ) ? false : get_option( "{$size}_crop" );
789 $_sizes[ $size ] = array( 'width' => $width, 'height' => $height, 'crop' => $crop );
792 $meta['sizes'] = array_merge( $meta['sizes'], $img->multi_resize( $_sizes ) );
798 wp_update_attachment_metadata( $post_id, $meta );
799 update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes);
801 if ( $target == 'thumbnail' || $target == 'all' || $target == 'full' ) {
802 // Check if it's an image edit from attachment edit screen
803 if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' == $_REQUEST['context'] ) {
804 $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true );
805 $return->thumbnail = $thumb_url[0];
807 $file_url = wp_get_attachment_url($post_id);
808 if ( ! empty( $meta['sizes']['thumbnail'] ) && $thumb = $meta['sizes']['thumbnail'] ) {
809 $return->thumbnail = path_join( dirname($file_url), $thumb['file'] );
811 $return->thumbnail = "$file_url?w=128&h=128";
821 /** This filter is documented in wp-admin/custom-header.php */
822 $delpath = apply_filters( 'wp_delete_file', $new_path );
826 $return->msg = esc_js( __('Image saved') );