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">
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 <h3><?php _e( 'Scale Image' ); ?> <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
50 <div class="imgedit-help">
51 <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>
53 <?php if ( isset( $meta['width'], $meta['height'] ) ): ?>
54 <p><?php printf( __('Original dimensions %s'), $meta['width'] . ' × ' . $meta['height'] ); ?></p>
56 <div class="imgedit-submit">
57 <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; ?>" />
58 <span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php echo $post_id; ?>">!</span></span>
59 <input type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'scale')" class="button button-primary" value="<?php esc_attr_e( 'Scale' ); ?>" />
64 <?php if ( $can_restore ) { ?>
66 <div class="imgedit-group">
67 <div class="imgedit-group-top">
68 <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>
69 <div class="imgedit-help">
70 <p><?php _e('Discard any changes and restore the original image.');
72 if ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE )
73 echo ' '.__('Previously edited copies of the image will not be deleted.');
76 <div class="imgedit-submit">
77 <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; ?> />
85 <div class="imgedit-group">
86 <div class="imgedit-group-top">
87 <h3><?php _e('Image Crop'); ?> <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
89 <div class="imgedit-help">
90 <p><?php _e('To crop the image, click on it and drag to make your selection.'); ?></p>
92 <p><strong><?php _e('Crop Aspect Ratio'); ?></strong><br />
93 <?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>
95 <p><strong><?php _e('Crop Selection'); ?></strong><br />
96 <?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>
101 <?php _e('Aspect ratio:'); ?>
102 <span class="nowrap">
103 <input type="text" id="imgedit-crop-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" style="width:3em;" />
105 <input type="text" id="imgedit-crop-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" style="width:3em;" />
109 <p id="imgedit-crop-sel-<?php echo $post_id; ?>">
110 <?php _e('Selection:'); ?>
111 <span class="nowrap">
112 <input type="text" id="imgedit-sel-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" style="width:4em;" />
114 <input type="text" id="imgedit-sel-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" style="width:4em;" />
119 <?php if ( $thumb && $sub_sizes ) {
120 $thumb_img = wp_constrain_dimensions( $thumb['width'], $thumb['height'], 160, 120 );
123 <div class="imgedit-group imgedit-applyto">
124 <div class="imgedit-group-top">
125 <h3><?php _e('Thumbnail Settings'); ?> <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
126 <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>
130 <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" />
131 <br /><?php _e('Current thumbnail'); ?>
134 <p id="imgedit-save-target-<?php echo $post_id; ?>">
135 <strong><?php _e('Apply changes to:'); ?></strong><br />
137 <label class="imgedit-label">
138 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="all" checked="checked" />
139 <?php _e('All image sizes'); ?></label>
141 <label class="imgedit-label">
142 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="thumbnail" />
143 <?php _e('Thumbnail'); ?></label>
145 <label class="imgedit-label">
146 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="nothumb" />
147 <?php _e('All sizes except thumbnail'); ?></label>
155 <div class="imgedit-panel-content">
157 <div class="imgedit-menu">
158 <div onclick="imageEdit.crop(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-crop disabled" title="<?php esc_attr_e( 'Crop' ); ?>"></div><?php
160 // On some setups GD library does not provide imagerotate() - Ticket #11536
161 if ( wp_image_editor_supports( array( 'mime_type' => get_post_mime_type( $post_id ), 'methods' => array( 'rotate' ) ) ) ) { ?>
162 <div class="imgedit-rleft" onclick="imageEdit.rotate( 90, <?php echo "$post_id, '$nonce'"; ?>, this)" title="<?php esc_attr_e( 'Rotate counter-clockwise' ); ?>"></div>
163 <div class="imgedit-rright" onclick="imageEdit.rotate(-90, <?php echo "$post_id, '$nonce'"; ?>, this)" title="<?php esc_attr_e( 'Rotate clockwise' ); ?>"></div>
165 $note_no_rotate = esc_attr__('Image rotation is not supported by your web host.');
167 <div class="imgedit-rleft disabled" title="<?php echo $note_no_rotate; ?>"></div>
168 <div class="imgedit-rright disabled" title="<?php echo $note_no_rotate; ?>"></div>
171 <div onclick="imageEdit.flip(1, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-flipv" title="<?php esc_attr_e( 'Flip vertically' ); ?>"></div>
172 <div onclick="imageEdit.flip(2, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-fliph" title="<?php esc_attr_e( 'Flip horizontally' ); ?>"></div>
174 <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>
175 <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>
179 <input type="hidden" id="imgedit-sizer-<?php echo $post_id; ?>" value="<?php echo $sizer; ?>" />
180 <input type="hidden" id="imgedit-history-<?php echo $post_id; ?>" value="" />
181 <input type="hidden" id="imgedit-undone-<?php echo $post_id; ?>" value="0" />
182 <input type="hidden" id="imgedit-selection-<?php echo $post_id; ?>" value="" />
183 <input type="hidden" id="imgedit-x-<?php echo $post_id; ?>" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
184 <input type="hidden" id="imgedit-y-<?php echo $post_id; ?>" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
186 <div id="imgedit-crop-<?php echo $post_id; ?>" class="imgedit-crop-wrap">
187 <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); ?>" />
190 <div class="imgedit-submit">
191 <input type="button" onclick="imageEdit.close(<?php echo $post_id; ?>, 1)" class="button" value="<?php esc_attr_e( 'Cancel' ); ?>" />
192 <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' ); ?>" />
197 <div class="imgedit-wait" id="imgedit-wait-<?php echo $post_id; ?>"></div>
198 <script type="text/javascript">jQuery( function() { imageEdit.init(<?php echo $post_id; ?>); });</script>
199 <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>
205 * Streams image in WP_Image_Editor to browser.
206 * Provided for backcompat reasons
208 * @param WP_Image_Editor $image
209 * @param string $mime_type
210 * @param int $post_id
213 function wp_stream_image( $image, $mime_type, $post_id ) {
214 if ( $image instanceof WP_Image_Editor ) {
217 * Filter the WP_Image_Editor instance for the image to be streamed to the browser.
221 * @param WP_Image_Editor $image WP_Image_Editor instance.
222 * @param int $post_id Post ID.
224 $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
226 if ( is_wp_error( $image->stream( $mime_type ) ) )
231 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
234 * Filter the GD image resource to be streamed to the browser.
237 * @deprecated 3.5.0 Use image_editor_save_pre instead.
239 * @param resource $image Image resource to be streamed.
240 * @param int $post_id Post ID.
242 $image = apply_filters( 'image_save_pre', $image, $post_id );
244 switch ( $mime_type ) {
246 header( 'Content-Type: image/jpeg' );
247 return imagejpeg( $image, null, 90 );
249 header( 'Content-Type: image/png' );
250 return imagepng( $image );
252 header( 'Content-Type: image/gif' );
253 return imagegif( $image );
261 * Saves Image to File
263 * @param string $filename
264 * @param WP_Image_Editor $image
265 * @param string $mime_type
266 * @param int $post_id
269 function wp_save_image_file( $filename, $image, $mime_type, $post_id ) {
270 if ( $image instanceof WP_Image_Editor ) {
272 /** This filter is documented in wp-admin/includes/image-edit.php */
273 $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
276 * Filter whether to skip saving the image file.
278 * Returning a non-null value will short-circuit the save method,
279 * returning that value instead.
283 * @param mixed $override Value to return instead of saving. Default null.
284 * @param string $filename Name of the file to be saved.
285 * @param WP_Image_Editor $image WP_Image_Editor instance.
286 * @param string $mime_type Image mime type.
287 * @param int $post_id Post ID.
289 $saved = apply_filters( 'wp_save_image_editor_file', null, $filename, $image, $mime_type, $post_id );
291 if ( null !== $saved )
294 return $image->save( $filename, $mime_type );
296 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
298 /** This filter is documented in wp-admin/includes/image-edit.php */
299 $image = apply_filters( 'image_save_pre', $image, $post_id );
302 * Filter whether to skip saving the image file.
304 * Returning a non-null value will short-circuit the save method,
305 * returning that value instead.
308 * @deprecated 3.5.0 Use wp_save_image_editor_file instead.
310 * @param mixed $override Value to return instead of saving. Default null.
311 * @param string $filename Name of the file to be saved.
312 * @param WP_Image_Editor $image WP_Image_Editor instance.
313 * @param string $mime_type Image mime type.
314 * @param int $post_id Post ID.
316 $saved = apply_filters( 'wp_save_image_file', null, $filename, $image, $mime_type, $post_id );
318 if ( null !== $saved )
321 switch ( $mime_type ) {
324 /** This filter is documented in wp-includes/class-wp-image-editor.php */
325 return imagejpeg( $image, $filename, apply_filters( 'jpeg_quality', 90, 'edit_image' ) );
327 return imagepng( $image, $filename );
329 return imagegif( $image, $filename );
337 * Image preview ratio. Internal use only.
342 * @param int $w Image width in pixels.
343 * @param int $h Image height in pixels.
344 * @return float|int Image preview ratio.
346 function _image_get_preview_ratio($w, $h) {
348 return $max > 400 ? (400 / $max) : 1;
352 * Returns an image resource. Internal use only.
357 * @param resource $img Image resource.
358 * @param float|int $angle Image rotation angle, in degrees.
359 * @return resource|false GD image resource, false otherwise.
361 function _rotate_image_resource($img, $angle) {
362 _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::rotate' ) );
363 if ( function_exists('imagerotate') ) {
364 $rotated = imagerotate($img, $angle, 0);
365 if ( is_resource($rotated) ) {
374 * Flips an image resource. Internal use only.
379 * @param resource $img Image resource.
380 * @param bool $horz Whether to flip horizontally.
381 * @param bool $vert Whether to flip vertically.
382 * @return resource (maybe) flipped image resource.
384 function _flip_image_resource($img, $horz, $vert) {
385 _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::flip' ) );
388 $dst = wp_imagecreatetruecolor($w, $h);
389 if ( is_resource($dst) ) {
390 $sx = $vert ? ($w - 1) : 0;
391 $sy = $horz ? ($h - 1) : 0;
392 $sw = $vert ? -$w : $w;
393 $sh = $horz ? -$h : $h;
395 if ( imagecopyresampled($dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh) ) {
404 * Crops an image resource. Internal use only.
409 * @param resource $img Image resource.
410 * @param float $x Source point x-coordinate.
411 * @param float $y Source point y-cooredinate.
412 * @param float $w Source width.
413 * @param float $h Source height.
414 * @return resource (maybe) cropped image resource.
416 function _crop_image_resource($img, $x, $y, $w, $h) {
417 $dst = wp_imagecreatetruecolor($w, $h);
418 if ( is_resource($dst) ) {
419 if ( imagecopy($dst, $img, 0, 0, $x, $y, $w, $h) ) {
428 * Performs group of changes on Editor specified.
432 * @param WP_Image_Editor $image {@see WP_Image_Editor} instance.
433 * @param array $changes Array of change operations.
434 * @return WP_Image_Editor {@see WP_Image_Editor} instance with changes applied.
436 function image_edit_apply_changes( $image, $changes ) {
437 if ( is_resource( $image ) )
438 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
440 if ( !is_array($changes) )
443 // Expand change operations.
444 foreach ( $changes as $key => $obj ) {
445 if ( isset($obj->r) ) {
446 $obj->type = 'rotate';
447 $obj->angle = $obj->r;
449 } elseif ( isset($obj->f) ) {
451 $obj->axis = $obj->f;
453 } elseif ( isset($obj->c) ) {
458 $changes[$key] = $obj;
461 // Combine operations.
462 if ( count($changes) > 1 ) {
463 $filtered = array($changes[0]);
464 for ( $i = 0, $j = 1, $c = count( $changes ); $j < $c; $j++ ) {
466 if ( $filtered[$i]->type == $changes[$j]->type ) {
467 switch ( $filtered[$i]->type ) {
469 $filtered[$i]->angle += $changes[$j]->angle;
473 $filtered[$i]->axis ^= $changes[$j]->axis;
479 $filtered[++$i] = $changes[$j];
481 $changes = $filtered;
485 // Image resource before applying the changes.
486 if ( $image instanceof WP_Image_Editor ) {
489 * Filter the WP_Image_Editor instance before applying changes to the image.
493 * @param WP_Image_Editor $image WP_Image_Editor instance.
494 * @param array $changes Array of change operations.
496 $image = apply_filters( 'wp_image_editor_before_change', $image, $changes );
497 } elseif ( is_resource( $image ) ) {
500 * Filter the GD image resource before applying changes to the image.
503 * @deprecated 3.5.0 Use wp_image_editor_before_change instead.
505 * @param resource $image GD image resource.
506 * @param array $changes Array of change operations.
508 $image = apply_filters( 'image_edit_before_change', $image, $changes );
511 foreach ( $changes as $operation ) {
512 switch ( $operation->type ) {
514 if ( $operation->angle != 0 ) {
515 if ( $image instanceof WP_Image_Editor )
516 $image->rotate( $operation->angle );
518 $image = _rotate_image_resource( $image, $operation->angle );
522 if ( $operation->axis != 0 )
523 if ( $image instanceof WP_Image_Editor )
524 $image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 );
526 $image = _flip_image_resource( $image, ( $operation->axis & 1 ) != 0, ( $operation->axis & 2 ) != 0 );
529 $sel = $operation->sel;
531 if ( $image instanceof WP_Image_Editor ) {
532 $size = $image->get_size();
534 $h = $size['height'];
536 $scale = 1 / _image_get_preview_ratio( $w, $h ); // discard preview scaling
537 $image->crop( $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
539 $scale = 1 / _image_get_preview_ratio( imagesx( $image ), imagesy( $image ) ); // discard preview scaling
540 $image = _crop_image_resource( $image, $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
551 * Streams image in post to browser, along with enqueued changes
552 * in $_REQUEST['history']
554 * @param int $post_id
557 function stream_preview_image( $post_id ) {
558 $post = get_post( $post_id );
560 /** This filter is documented in wp-admin/admin.php */
561 @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
563 $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) );
565 if ( is_wp_error( $img ) )
568 $changes = !empty($_REQUEST['history']) ? json_decode( wp_unslash($_REQUEST['history']) ) : null;
570 $img = image_edit_apply_changes( $img, $changes );
573 $size = $img->get_size();
575 $h = $size['height'];
577 $ratio = _image_get_preview_ratio( $w, $h );
578 $w2 = max ( 1, $w * $ratio );
579 $h2 = max ( 1, $h * $ratio );
581 if ( is_wp_error( $img->resize( $w2, $h2 ) ) )
584 return wp_stream_image( $img, $post->post_mime_type, $post_id );
588 * Restores the metadata for a given attachment.
592 * @param int $post_id Attachment post ID.
593 * @return stdClass Image restoration message object.
595 function wp_restore_image($post_id) {
596 $meta = wp_get_attachment_metadata($post_id);
597 $file = get_attached_file($post_id);
598 $backup_sizes = $old_backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
602 if ( !is_array($backup_sizes) ) {
603 $msg->error = __('Cannot load image metadata.');
607 $parts = pathinfo($file);
608 $suffix = time() . rand(100, 999);
609 $default_sizes = get_intermediate_image_sizes();
611 if ( isset($backup_sizes['full-orig']) && is_array($backup_sizes['full-orig']) ) {
612 $data = $backup_sizes['full-orig'];
614 if ( $parts['basename'] != $data['file'] ) {
615 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
617 // Delete only if it's edited image.
618 if ( preg_match('/-e[0-9]{13}\./', $parts['basename']) ) {
619 wp_delete_file( $file );
621 } elseif ( isset( $meta['width'], $meta['height'] ) ) {
622 $backup_sizes["full-$suffix"] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $parts['basename']);
626 $restored_file = path_join($parts['dirname'], $data['file']);
627 $restored = update_attached_file($post_id, $restored_file);
629 $meta['file'] = _wp_relative_upload_path( $restored_file );
630 $meta['width'] = $data['width'];
631 $meta['height'] = $data['height'];
634 foreach ( $default_sizes as $default_size ) {
635 if ( isset($backup_sizes["$default_size-orig"]) ) {
636 $data = $backup_sizes["$default_size-orig"];
637 if ( isset($meta['sizes'][$default_size]) && $meta['sizes'][$default_size]['file'] != $data['file'] ) {
638 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
640 // Delete only if it's edited image
641 if ( preg_match('/-e[0-9]{13}-/', $meta['sizes'][$default_size]['file']) ) {
642 $delete_file = path_join( $parts['dirname'], $meta['sizes'][$default_size]['file'] );
643 wp_delete_file( $delete_file );
646 $backup_sizes["$default_size-{$suffix}"] = $meta['sizes'][$default_size];
650 $meta['sizes'][$default_size] = $data;
652 unset($meta['sizes'][$default_size]);
656 if ( ! wp_update_attachment_metadata( $post_id, $meta ) ||
657 ( $old_backup_sizes !== $backup_sizes && ! update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ) ) ) {
659 $msg->error = __('Cannot save image metadata.');
664 $msg->error = __('Image metadata is inconsistent.');
666 $msg->msg = __('Image restored successfully.');
672 * Saves image to post along with enqueued changes
673 * in $_REQUEST['history']
675 * @param int $post_id
678 function wp_save_image( $post_id ) {
679 global $_wp_additional_image_sizes;
681 $return = new stdClass;
682 $success = $delete = $scaled = $nocrop = false;
683 $post = get_post( $post_id );
685 $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) );
686 if ( is_wp_error( $img ) ) {
687 $return->error = esc_js( __('Unable to create new image.') );
691 $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
692 $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
693 $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
694 $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
696 if ( $scale && $fwidth > 0 && $fheight > 0 ) {
697 $size = $img->get_size();
698 $sX = $size['width'];
699 $sY = $size['height'];
701 // Check if it has roughly the same w / h ratio.
702 $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
703 if ( -0.1 < $diff && $diff < 0.1 ) {
704 // Scale the full size image.
705 if ( $img->resize( $fwidth, $fheight ) )
710 $return->error = esc_js( __('Error while saving the scaled image. Please reload the page and try again.') );
713 } elseif ( !empty($_REQUEST['history']) ) {
714 $changes = json_decode( wp_unslash($_REQUEST['history']) );
716 $img = image_edit_apply_changes($img, $changes);
718 $return->error = esc_js( __('Nothing to save, the image has not changed.') );
722 $meta = wp_get_attachment_metadata($post_id);
723 $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
725 if ( !is_array($meta) ) {
726 $return->error = esc_js( __('Image data does not exist. Please re-upload the image.') );
730 if ( !is_array($backup_sizes) )
731 $backup_sizes = array();
733 // Generate new filename.
734 $path = get_attached_file($post_id);
735 $path_parts = pathinfo( $path );
736 $filename = $path_parts['filename'];
737 $suffix = time() . rand(100, 999);
739 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE &&
740 isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] ) {
742 if ( 'thumbnail' == $target )
743 $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}";
748 $filename = preg_replace( '/-e([0-9]+)$/', '', $filename );
749 $filename .= "-e{$suffix}";
750 $new_filename = "{$filename}.{$path_parts['extension']}";
751 $new_path = "{$path_parts['dirname']}/$new_filename";
752 if ( file_exists($new_path) )
759 // Save the full-size file, also needed to create sub-sizes.
760 if ( !wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id) ) {
761 $return->error = esc_js( __('Unable to save the image.') );
765 if ( 'nothumb' == $target || 'all' == $target || 'full' == $target || $scaled ) {
767 if ( isset($backup_sizes['full-orig']) ) {
768 if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] )
769 $tag = "full-$suffix";
775 $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']);
777 $success = ( $path === $new_path ) || update_attached_file( $post_id, $new_path );
779 $meta['file'] = _wp_relative_upload_path( $new_path );
781 $size = $img->get_size();
782 $meta['width'] = $size['width'];
783 $meta['height'] = $size['height'];
785 if ( $success && ('nothumb' == $target || 'all' == $target) ) {
786 $sizes = get_intermediate_image_sizes();
787 if ( 'nothumb' == $target )
788 $sizes = array_diff( $sizes, array('thumbnail') );
791 $return->fw = $meta['width'];
792 $return->fh = $meta['height'];
793 } elseif ( 'thumbnail' == $target ) {
794 $sizes = array( 'thumbnail' );
795 $success = $delete = $nocrop = true;
798 if ( isset( $sizes ) ) {
801 foreach ( $sizes as $size ) {
803 if ( isset( $meta['sizes'][$size] ) ) {
804 if ( isset($backup_sizes["$size-orig"]) ) {
805 if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes["$size-orig"]['file'] != $meta['sizes'][$size]['file'] )
806 $tag = "$size-$suffix";
812 $backup_sizes[$tag] = $meta['sizes'][$size];
815 if ( isset( $_wp_additional_image_sizes[ $size ] ) ) {
816 $width = intval( $_wp_additional_image_sizes[ $size ]['width'] );
817 $height = intval( $_wp_additional_image_sizes[ $size ]['height'] );
818 $crop = ( $nocrop ) ? false : $_wp_additional_image_sizes[ $size ]['crop'];
820 $height = get_option( "{$size}_size_h" );
821 $width = get_option( "{$size}_size_w" );
822 $crop = ( $nocrop ) ? false : get_option( "{$size}_crop" );
825 $_sizes[ $size ] = array( 'width' => $width, 'height' => $height, 'crop' => $crop );
828 $meta['sizes'] = array_merge( $meta['sizes'], $img->multi_resize( $_sizes ) );
834 wp_update_attachment_metadata( $post_id, $meta );
835 update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes);
837 if ( $target == 'thumbnail' || $target == 'all' || $target == 'full' ) {
838 // Check if it's an image edit from attachment edit screen
839 if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' == $_REQUEST['context'] ) {
840 $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true );
841 $return->thumbnail = $thumb_url[0];
843 $file_url = wp_get_attachment_url($post_id);
844 if ( ! empty( $meta['sizes']['thumbnail'] ) && $thumb = $meta['sizes']['thumbnail'] ) {
845 $return->thumbnail = path_join( dirname($file_url), $thumb['file'] );
847 $return->thumbnail = "$file_url?w=128&h=128";
856 wp_delete_file( $new_path );
859 $return->msg = esc_js( __('Image saved') );