3 * WordPress Image Editor
6 * @subpackage Administration
10 * Loads the WP image-editing interface.
12 * @param int $post_id Post ID.
13 * @param bool|object $msg Optional. Message to display for image editor updates or errors.
16 function wp_image_editor($post_id, $msg = false) {
17 $nonce = wp_create_nonce("image_editor-$post_id");
18 $meta = wp_get_attachment_metadata($post_id);
19 $thumb = image_get_intermediate_size($post_id, 'thumbnail');
20 $sub_sizes = isset($meta['sizes']) && is_array($meta['sizes']);
23 if ( isset( $meta['width'], $meta['height'] ) )
24 $big = max( $meta['width'], $meta['height'] );
26 die( __('Image data does not exist. Please re-upload the image.') );
28 $sizer = $big > 400 ? 400 / $big : 1;
30 $backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
32 if ( ! empty( $backup_sizes ) && isset( $backup_sizes['full-orig'], $meta['file'] ) )
33 $can_restore = $backup_sizes['full-orig']['file'] != basename( $meta['file'] );
36 if ( isset($msg->error) )
37 $note = "<div class='error'><p>$msg->error</p></div>";
38 elseif ( isset($msg->msg) )
39 $note = "<div class='updated'><p>$msg->msg</p></div>";
43 <div class="imgedit-wrap wp-clearfix">
44 <div id="imgedit-panel-<?php echo $post_id; ?>">
46 <div class="imgedit-settings">
47 <div class="imgedit-group">
48 <div class="imgedit-group-top">
49 <h2><?php _e( 'Scale Image' ); ?></h2>
50 <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Scale Image Help' ); ?></span></button>
51 <div class="imgedit-help">
52 <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>
54 <?php if ( isset( $meta['width'], $meta['height'] ) ): ?>
55 <p><?php printf( __('Original dimensions %s'), $meta['width'] . ' × ' . $meta['height'] ); ?></p>
57 <div class="imgedit-submit">
59 <fieldset class="imgedit-scale">
60 <legend><?php _e( 'New dimensions:' ); ?></legend>
62 <label><span class="screen-reader-text"><?php _e( 'scale width' ); ?></span>
63 <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)" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
65 <span class="imgedit-separator">×</span>
66 <label><span class="screen-reader-text"><?php _e( 'scale height' ); ?></span>
67 <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)" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
69 <span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php echo $post_id; ?>">!</span>
70 <input id="imgedit-scale-button" type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'scale')" class="button button-primary" value="<?php esc_attr_e( 'Scale' ); ?>" />
78 <?php if ( $can_restore ) { ?>
80 <div class="imgedit-group">
81 <div class="imgedit-group-top">
82 <h2><button type="button" onclick="imageEdit.toggleHelp(this);" class="button-link"><?php _e( 'Restore Original Image' ); ?> <span class="dashicons dashicons-arrow-down imgedit-help-toggle"></span></button></h2>
83 <div class="imgedit-help">
84 <p><?php _e('Discard any changes and restore the original image.');
86 if ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE )
87 echo ' '.__('Previously edited copies of the image will not be deleted.');
90 <div class="imgedit-submit">
91 <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; ?> />
99 <div class="imgedit-group">
100 <div class="imgedit-group-top">
101 <h2><?php _e( 'Image Crop' ); ?></h2>
102 <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Image Crop Help' ); ?></span></button>
104 <div class="imgedit-help">
105 <p><?php _e('To crop the image, click on it and drag to make your selection.'); ?></p>
107 <p><strong><?php _e('Crop Aspect Ratio'); ?></strong><br />
108 <?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>
110 <p><strong><?php _e('Crop Selection'); ?></strong><br />
111 <?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>
115 <fieldset class="imgedit-crop-ratio">
116 <legend><?php _e( 'Aspect ratio:' ); ?></legend>
118 <label><span class="screen-reader-text"><?php _e( 'crop ratio width' ); ?></span>
119 <input type="text" id="imgedit-crop-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" />
121 <span class="imgedit-separator">:</span>
122 <label><span class="screen-reader-text"><?php _e( 'crop ratio height' ); ?></span>
123 <input type="text" id="imgedit-crop-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" />
128 <fieldset id="imgedit-crop-sel-<?php echo $post_id; ?>" class="imgedit-crop-sel">
129 <legend><?php _e( 'Selection:' ); ?></legend>
131 <label><span class="screen-reader-text"><?php _e( 'selection width' ); ?></span>
132 <input type="text" id="imgedit-sel-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" />
134 <span class="imgedit-separator">×</span>
135 <label><span class="screen-reader-text"><?php _e( 'selection height' ); ?></span>
136 <input type="text" id="imgedit-sel-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" />
143 <?php if ( $thumb && $sub_sizes ) {
144 $thumb_img = wp_constrain_dimensions( $thumb['width'], $thumb['height'], 160, 120 );
147 <div class="imgedit-group imgedit-applyto">
148 <div class="imgedit-group-top">
149 <h2><?php _e( 'Thumbnail Settings' ); ?></h2>
150 <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Thumbnail Settings Help' ); ?></span></button>
151 <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>
154 <figure class="imgedit-thumbnail-preview">
155 <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" />
156 <figcaption class="imgedit-thumbnail-preview-caption"><?php _e( 'Current thumbnail' ); ?></figcaption>
159 <div id="imgedit-save-target-<?php echo $post_id; ?>" class="imgedit-save-target">
161 <legend><strong><?php _e( 'Apply changes to:' ); ?></strong></legend>
163 <label class="imgedit-label">
164 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="all" checked="checked" />
165 <?php _e('All image sizes'); ?></label>
167 <label class="imgedit-label">
168 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="thumbnail" />
169 <?php _e('Thumbnail'); ?></label>
171 <label class="imgedit-label">
172 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="nothumb" />
173 <?php _e('All sizes except thumbnail'); ?></label>
182 <div class="imgedit-panel-content wp-clearfix">
184 <div class="imgedit-menu wp-clearfix">
185 <button type="button" onclick="imageEdit.crop(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-crop button disabled" disabled><span class="screen-reader-text"><?php esc_html_e( 'Crop' ); ?></span></button><?php
187 // On some setups GD library does not provide imagerotate() - Ticket #11536
188 if ( wp_image_editor_supports( array( 'mime_type' => get_post_mime_type( $post_id ), 'methods' => array( 'rotate' ) ) ) ) {
189 $note_no_rotate = '';
191 <button type="button" class="imgedit-rleft button" onclick="imageEdit.rotate( 90, <?php echo "$post_id, '$nonce'"; ?>, this)"><span class="screen-reader-text"><?php esc_html_e( 'Rotate counter-clockwise' ); ?></span></button>
192 <button type="button" class="imgedit-rright button" onclick="imageEdit.rotate(-90, <?php echo "$post_id, '$nonce'"; ?>, this)"><span class="screen-reader-text"><?php esc_html_e( 'Rotate clockwise' ); ?></span></button>
194 $note_no_rotate = '<p class="note-no-rotate"><em>' . __( 'Image rotation is not supported by your web host.' ) . '</em></p>';
196 <button type="button" class="imgedit-rleft button disabled" disabled></button>
197 <button type="button" class="imgedit-rright button disabled" disabled></button>
200 <button type="button" onclick="imageEdit.flip(1, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-flipv button"><span class="screen-reader-text"><?php esc_html_e( 'Flip vertically' ); ?></span></button>
201 <button type="button" onclick="imageEdit.flip(2, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-fliph button"><span class="screen-reader-text"><?php esc_html_e( 'Flip horizontally' ); ?></span></button>
203 <button type="button" id="image-undo-<?php echo $post_id; ?>" onclick="imageEdit.undo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-undo button disabled" disabled><span class="screen-reader-text"><?php esc_html_e( 'Undo' ); ?></span></button>
204 <button type="button" id="image-redo-<?php echo $post_id; ?>" onclick="imageEdit.redo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-redo button disabled" disabled><span class="screen-reader-text"><?php esc_html_e( 'Redo' ); ?></span></button>
205 <?php echo $note_no_rotate; ?>
208 <input type="hidden" id="imgedit-sizer-<?php echo $post_id; ?>" value="<?php echo $sizer; ?>" />
209 <input type="hidden" id="imgedit-history-<?php echo $post_id; ?>" value="" />
210 <input type="hidden" id="imgedit-undone-<?php echo $post_id; ?>" value="0" />
211 <input type="hidden" id="imgedit-selection-<?php echo $post_id; ?>" value="" />
212 <input type="hidden" id="imgedit-x-<?php echo $post_id; ?>" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
213 <input type="hidden" id="imgedit-y-<?php echo $post_id; ?>" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
215 <div id="imgedit-crop-<?php echo $post_id; ?>" class="imgedit-crop-wrap">
216 <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); ?>" alt="" />
219 <div class="imgedit-submit">
220 <input type="button" onclick="imageEdit.close(<?php echo $post_id; ?>, 1)" class="button imgedit-cancel-btn" value="<?php esc_attr_e( 'Cancel' ); ?>" />
221 <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' ); ?>" />
226 <div class="imgedit-wait" id="imgedit-wait-<?php echo $post_id; ?>"></div>
227 <script type="text/javascript">jQuery( function() { imageEdit.init(<?php echo $post_id; ?>); });</script>
228 <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>
234 * Streams image in WP_Image_Editor to browser.
235 * Provided for backcompat reasons
237 * @param WP_Image_Editor $image
238 * @param string $mime_type
239 * @param int $post_id
242 function wp_stream_image( $image, $mime_type, $post_id ) {
243 if ( $image instanceof WP_Image_Editor ) {
246 * Filter the WP_Image_Editor instance for the image to be streamed to the browser.
250 * @param WP_Image_Editor $image WP_Image_Editor instance.
251 * @param int $post_id Post ID.
253 $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
255 if ( is_wp_error( $image->stream( $mime_type ) ) )
260 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
263 * Filter the GD image resource to be streamed to the browser.
266 * @deprecated 3.5.0 Use image_editor_save_pre instead.
268 * @param resource $image Image resource to be streamed.
269 * @param int $post_id Post ID.
271 $image = apply_filters( 'image_save_pre', $image, $post_id );
273 switch ( $mime_type ) {
275 header( 'Content-Type: image/jpeg' );
276 return imagejpeg( $image, null, 90 );
278 header( 'Content-Type: image/png' );
279 return imagepng( $image );
281 header( 'Content-Type: image/gif' );
282 return imagegif( $image );
290 * Saves Image to File
292 * @param string $filename
293 * @param WP_Image_Editor $image
294 * @param string $mime_type
295 * @param int $post_id
298 function wp_save_image_file( $filename, $image, $mime_type, $post_id ) {
299 if ( $image instanceof WP_Image_Editor ) {
301 /** This filter is documented in wp-admin/includes/image-edit.php */
302 $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
305 * Filter whether to skip saving the image file.
307 * Returning a non-null value will short-circuit the save method,
308 * returning that value instead.
312 * @param mixed $override Value to return instead of saving. Default null.
313 * @param string $filename Name of the file to be saved.
314 * @param WP_Image_Editor $image WP_Image_Editor instance.
315 * @param string $mime_type Image mime type.
316 * @param int $post_id Post ID.
318 $saved = apply_filters( 'wp_save_image_editor_file', null, $filename, $image, $mime_type, $post_id );
320 if ( null !== $saved )
323 return $image->save( $filename, $mime_type );
325 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
327 /** This filter is documented in wp-admin/includes/image-edit.php */
328 $image = apply_filters( 'image_save_pre', $image, $post_id );
331 * Filter whether to skip saving the image file.
333 * Returning a non-null value will short-circuit the save method,
334 * returning that value instead.
337 * @deprecated 3.5.0 Use wp_save_image_editor_file instead.
339 * @param mixed $override Value to return instead of saving. Default null.
340 * @param string $filename Name of the file to be saved.
341 * @param WP_Image_Editor $image WP_Image_Editor instance.
342 * @param string $mime_type Image mime type.
343 * @param int $post_id Post ID.
345 $saved = apply_filters( 'wp_save_image_file', null, $filename, $image, $mime_type, $post_id );
347 if ( null !== $saved )
350 switch ( $mime_type ) {
353 /** This filter is documented in wp-includes/class-wp-image-editor.php */
354 return imagejpeg( $image, $filename, apply_filters( 'jpeg_quality', 90, 'edit_image' ) );
356 return imagepng( $image, $filename );
358 return imagegif( $image, $filename );
366 * Image preview ratio. Internal use only.
371 * @param int $w Image width in pixels.
372 * @param int $h Image height in pixels.
373 * @return float|int Image preview ratio.
375 function _image_get_preview_ratio($w, $h) {
377 return $max > 400 ? (400 / $max) : 1;
381 * Returns an image resource. Internal use only.
386 * @param resource $img Image resource.
387 * @param float|int $angle Image rotation angle, in degrees.
388 * @return resource|false GD image resource, false otherwise.
390 function _rotate_image_resource($img, $angle) {
391 _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::rotate' ) );
392 if ( function_exists('imagerotate') ) {
393 $rotated = imagerotate($img, $angle, 0);
394 if ( is_resource($rotated) ) {
403 * Flips an image resource. Internal use only.
408 * @param resource $img Image resource.
409 * @param bool $horz Whether to flip horizontally.
410 * @param bool $vert Whether to flip vertically.
411 * @return resource (maybe) flipped image resource.
413 function _flip_image_resource($img, $horz, $vert) {
414 _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::flip' ) );
417 $dst = wp_imagecreatetruecolor($w, $h);
418 if ( is_resource($dst) ) {
419 $sx = $vert ? ($w - 1) : 0;
420 $sy = $horz ? ($h - 1) : 0;
421 $sw = $vert ? -$w : $w;
422 $sh = $horz ? -$h : $h;
424 if ( imagecopyresampled($dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh) ) {
433 * Crops an image resource. Internal use only.
438 * @param resource $img Image resource.
439 * @param float $x Source point x-coordinate.
440 * @param float $y Source point y-cooredinate.
441 * @param float $w Source width.
442 * @param float $h Source height.
443 * @return resource (maybe) cropped image resource.
445 function _crop_image_resource($img, $x, $y, $w, $h) {
446 $dst = wp_imagecreatetruecolor($w, $h);
447 if ( is_resource($dst) ) {
448 if ( imagecopy($dst, $img, 0, 0, $x, $y, $w, $h) ) {
457 * Performs group of changes on Editor specified.
461 * @param WP_Image_Editor $image {@see WP_Image_Editor} instance.
462 * @param array $changes Array of change operations.
463 * @return WP_Image_Editor {@see WP_Image_Editor} instance with changes applied.
465 function image_edit_apply_changes( $image, $changes ) {
466 if ( is_resource( $image ) )
467 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
469 if ( !is_array($changes) )
472 // Expand change operations.
473 foreach ( $changes as $key => $obj ) {
474 if ( isset($obj->r) ) {
475 $obj->type = 'rotate';
476 $obj->angle = $obj->r;
478 } elseif ( isset($obj->f) ) {
480 $obj->axis = $obj->f;
482 } elseif ( isset($obj->c) ) {
487 $changes[$key] = $obj;
490 // Combine operations.
491 if ( count($changes) > 1 ) {
492 $filtered = array($changes[0]);
493 for ( $i = 0, $j = 1, $c = count( $changes ); $j < $c; $j++ ) {
495 if ( $filtered[$i]->type == $changes[$j]->type ) {
496 switch ( $filtered[$i]->type ) {
498 $filtered[$i]->angle += $changes[$j]->angle;
502 $filtered[$i]->axis ^= $changes[$j]->axis;
508 $filtered[++$i] = $changes[$j];
510 $changes = $filtered;
514 // Image resource before applying the changes.
515 if ( $image instanceof WP_Image_Editor ) {
518 * Filter the WP_Image_Editor instance before applying changes to the image.
522 * @param WP_Image_Editor $image WP_Image_Editor instance.
523 * @param array $changes Array of change operations.
525 $image = apply_filters( 'wp_image_editor_before_change', $image, $changes );
526 } elseif ( is_resource( $image ) ) {
529 * Filter the GD image resource before applying changes to the image.
532 * @deprecated 3.5.0 Use wp_image_editor_before_change instead.
534 * @param resource $image GD image resource.
535 * @param array $changes Array of change operations.
537 $image = apply_filters( 'image_edit_before_change', $image, $changes );
540 foreach ( $changes as $operation ) {
541 switch ( $operation->type ) {
543 if ( $operation->angle != 0 ) {
544 if ( $image instanceof WP_Image_Editor )
545 $image->rotate( $operation->angle );
547 $image = _rotate_image_resource( $image, $operation->angle );
551 if ( $operation->axis != 0 )
552 if ( $image instanceof WP_Image_Editor )
553 $image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 );
555 $image = _flip_image_resource( $image, ( $operation->axis & 1 ) != 0, ( $operation->axis & 2 ) != 0 );
558 $sel = $operation->sel;
560 if ( $image instanceof WP_Image_Editor ) {
561 $size = $image->get_size();
563 $h = $size['height'];
565 $scale = 1 / _image_get_preview_ratio( $w, $h ); // discard preview scaling
566 $image->crop( $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
568 $scale = 1 / _image_get_preview_ratio( imagesx( $image ), imagesy( $image ) ); // discard preview scaling
569 $image = _crop_image_resource( $image, $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
580 * Streams image in post to browser, along with enqueued changes
581 * in $_REQUEST['history']
583 * @param int $post_id
586 function stream_preview_image( $post_id ) {
587 $post = get_post( $post_id );
589 /** This filter is documented in wp-admin/admin.php */
590 @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
592 $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) );
594 if ( is_wp_error( $img ) ) {
598 $changes = !empty($_REQUEST['history']) ? json_decode( wp_unslash($_REQUEST['history']) ) : null;
600 $img = image_edit_apply_changes( $img, $changes );
603 $size = $img->get_size();
605 $h = $size['height'];
607 $ratio = _image_get_preview_ratio( $w, $h );
608 $w2 = max ( 1, $w * $ratio );
609 $h2 = max ( 1, $h * $ratio );
611 if ( is_wp_error( $img->resize( $w2, $h2 ) ) )
614 return wp_stream_image( $img, $post->post_mime_type, $post_id );
618 * Restores the metadata for a given attachment.
622 * @param int $post_id Attachment post ID.
623 * @return stdClass Image restoration message object.
625 function wp_restore_image($post_id) {
626 $meta = wp_get_attachment_metadata($post_id);
627 $file = get_attached_file($post_id);
628 $backup_sizes = $old_backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
632 if ( !is_array($backup_sizes) ) {
633 $msg->error = __('Cannot load image metadata.');
637 $parts = pathinfo($file);
638 $suffix = time() . rand(100, 999);
639 $default_sizes = get_intermediate_image_sizes();
641 if ( isset($backup_sizes['full-orig']) && is_array($backup_sizes['full-orig']) ) {
642 $data = $backup_sizes['full-orig'];
644 if ( $parts['basename'] != $data['file'] ) {
645 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
647 // Delete only if it's an edited image.
648 if ( preg_match('/-e[0-9]{13}\./', $parts['basename']) ) {
649 wp_delete_file( $file );
651 } elseif ( isset( $meta['width'], $meta['height'] ) ) {
652 $backup_sizes["full-$suffix"] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $parts['basename']);
656 $restored_file = path_join($parts['dirname'], $data['file']);
657 $restored = update_attached_file($post_id, $restored_file);
659 $meta['file'] = _wp_relative_upload_path( $restored_file );
660 $meta['width'] = $data['width'];
661 $meta['height'] = $data['height'];
664 foreach ( $default_sizes as $default_size ) {
665 if ( isset($backup_sizes["$default_size-orig"]) ) {
666 $data = $backup_sizes["$default_size-orig"];
667 if ( isset($meta['sizes'][$default_size]) && $meta['sizes'][$default_size]['file'] != $data['file'] ) {
668 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
670 // Delete only if it's an edited image.
671 if ( preg_match('/-e[0-9]{13}-/', $meta['sizes'][$default_size]['file']) ) {
672 $delete_file = path_join( $parts['dirname'], $meta['sizes'][$default_size]['file'] );
673 wp_delete_file( $delete_file );
676 $backup_sizes["$default_size-{$suffix}"] = $meta['sizes'][$default_size];
680 $meta['sizes'][$default_size] = $data;
682 unset($meta['sizes'][$default_size]);
686 if ( ! wp_update_attachment_metadata( $post_id, $meta ) ||
687 ( $old_backup_sizes !== $backup_sizes && ! update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ) ) ) {
689 $msg->error = __('Cannot save image metadata.');
694 $msg->error = __('Image metadata is inconsistent.');
696 $msg->msg = __('Image restored successfully.');
702 * Saves image to post along with enqueued changes
703 * in $_REQUEST['history']
705 * @global array $_wp_additional_image_sizes
707 * @param int $post_id
710 function wp_save_image( $post_id ) {
711 global $_wp_additional_image_sizes;
713 $return = new stdClass;
714 $success = $delete = $scaled = $nocrop = false;
715 $post = get_post( $post_id );
717 $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) );
718 if ( is_wp_error( $img ) ) {
719 $return->error = esc_js( __('Unable to create new image.') );
723 $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
724 $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
725 $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
726 $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
728 if ( $scale && $fwidth > 0 && $fheight > 0 ) {
729 $size = $img->get_size();
730 $sX = $size['width'];
731 $sY = $size['height'];
733 // Check if it has roughly the same w / h ratio.
734 $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
735 if ( -0.1 < $diff && $diff < 0.1 ) {
736 // Scale the full size image.
737 if ( $img->resize( $fwidth, $fheight ) )
742 $return->error = esc_js( __('Error while saving the scaled image. Please reload the page and try again.') );
745 } elseif ( !empty($_REQUEST['history']) ) {
746 $changes = json_decode( wp_unslash($_REQUEST['history']) );
748 $img = image_edit_apply_changes($img, $changes);
750 $return->error = esc_js( __('Nothing to save, the image has not changed.') );
754 $meta = wp_get_attachment_metadata($post_id);
755 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
757 if ( !is_array($meta) ) {
758 $return->error = esc_js( __('Image data does not exist. Please re-upload the image.') );
762 if ( !is_array($backup_sizes) )
763 $backup_sizes = array();
765 // Generate new filename.
766 $path = get_attached_file($post_id);
767 $path_parts = pathinfo( $path );
768 $filename = $path_parts['filename'];
769 $suffix = time() . rand(100, 999);
771 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE &&
772 isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] ) {
774 if ( 'thumbnail' == $target )
775 $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}";
780 $filename = preg_replace( '/-e([0-9]+)$/', '', $filename );
781 $filename .= "-e{$suffix}";
782 $new_filename = "{$filename}.{$path_parts['extension']}";
783 $new_path = "{$path_parts['dirname']}/$new_filename";
784 if ( file_exists($new_path) )
791 // Save the full-size file, also needed to create sub-sizes.
792 if ( !wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id) ) {
793 $return->error = esc_js( __('Unable to save the image.') );
797 if ( 'nothumb' == $target || 'all' == $target || 'full' == $target || $scaled ) {
799 if ( isset($backup_sizes['full-orig']) ) {
800 if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] )
801 $tag = "full-$suffix";
807 $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']);
809 $success = ( $path === $new_path ) || update_attached_file( $post_id, $new_path );
811 $meta['file'] = _wp_relative_upload_path( $new_path );
813 $size = $img->get_size();
814 $meta['width'] = $size['width'];
815 $meta['height'] = $size['height'];
817 if ( $success && ('nothumb' == $target || 'all' == $target) ) {
818 $sizes = get_intermediate_image_sizes();
819 if ( 'nothumb' == $target )
820 $sizes = array_diff( $sizes, array('thumbnail') );
823 $return->fw = $meta['width'];
824 $return->fh = $meta['height'];
825 } elseif ( 'thumbnail' == $target ) {
826 $sizes = array( 'thumbnail' );
827 $success = $delete = $nocrop = true;
830 if ( isset( $sizes ) ) {
833 foreach ( $sizes as $size ) {
835 if ( isset( $meta['sizes'][$size] ) ) {
836 if ( isset($backup_sizes["$size-orig"]) ) {
837 if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes["$size-orig"]['file'] != $meta['sizes'][$size]['file'] )
838 $tag = "$size-$suffix";
844 $backup_sizes[$tag] = $meta['sizes'][$size];
847 if ( isset( $_wp_additional_image_sizes[ $size ] ) ) {
848 $width = intval( $_wp_additional_image_sizes[ $size ]['width'] );
849 $height = intval( $_wp_additional_image_sizes[ $size ]['height'] );
850 $crop = ( $nocrop ) ? false : $_wp_additional_image_sizes[ $size ]['crop'];
852 $height = get_option( "{$size}_size_h" );
853 $width = get_option( "{$size}_size_w" );
854 $crop = ( $nocrop ) ? false : get_option( "{$size}_crop" );
857 $_sizes[ $size ] = array( 'width' => $width, 'height' => $height, 'crop' => $crop );
860 $meta['sizes'] = array_merge( $meta['sizes'], $img->multi_resize( $_sizes ) );
866 wp_update_attachment_metadata( $post_id, $meta );
867 update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes);
869 if ( $target == 'thumbnail' || $target == 'all' || $target == 'full' ) {
870 // Check if it's an image edit from attachment edit screen
871 if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' == $_REQUEST['context'] ) {
872 $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true );
873 $return->thumbnail = $thumb_url[0];
875 $file_url = wp_get_attachment_url($post_id);
876 if ( ! empty( $meta['sizes']['thumbnail'] ) && $thumb = $meta['sizes']['thumbnail'] ) {
877 $return->thumbnail = path_join( dirname($file_url), $thumb['file'] );
879 $return->thumbnail = "$file_url?w=128&h=128";
888 wp_delete_file( $new_path );
891 $return->msg = esc_js( __('Image saved') );