/** * From wp-admin/includes/image-edit.php */ function pte_stream_preview_image($post_id) { $post = get_post($post_id); @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT)); $img = wp_get_image_editor(_load_image_to_edit_path($post_id)); if (is_wp_error($img)) { return false; } // scale the image $size = $img->get_size(); $w = $size['width']; $h = $size['height']; $ratio = pte_image_get_preview_ratio($w, $h); $w2 = $w * $ratio; $h2 = $h * $ratio; if (is_wp_error($img->resize($w2, $h2))) { return false; } return wp_stream_image($img, $post->post_mime_type, $post_id); }
private static function _load_image_to_edit_path($attachment_id, $size = 'full') { $filepath = get_attached_file($attachment_id); if (function_exists('_load_image_to_edit_path') && file_exists($filepath)) { return _load_image_to_edit_path($attachment_id, $size); } if ($filepath) { if (file_exists($filepath)) { if ('full' != $size && ($data = image_get_intermediate_size($attachment_id, $size))) { $filepath = apply_filters('load_image_to_edit_filesystempath', path_join(dirname($filepath), $data['file']), $attachment_id, $size); } } else { // if file doesn't exist locally fetch the file and store in the location we're expecting it to be in... $response = wp_remote_get(wp_get_attachment_url($attachment_id)); if (wp_remote_retrieve_response_code($response) == 200) { if (!file_exists(dirname($filepath))) { mkdir(dirname($filepath), 0777, true); } file_put_contents($filepath, wp_remote_retrieve_body($response)); } } } return apply_filters('load_image_to_edit_path', $filepath, $attachment_id, $size); }
/** * Saves image to post along with enqueued changes * in $_REQUEST['history'] * * @param int $post_id * @return \stdClass */ function wp_save_image($post_id) { global $_wp_additional_image_sizes; $return = new stdClass(); $success = $delete = $scaled = $nocrop = false; $post = get_post($post_id); $img = wp_get_image_editor(_load_image_to_edit_path($post_id, 'full')); if (is_wp_error($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) { $size = $img->get_size(); $sX = $size['width']; $sY = $size['height']; // 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. if ($img->resize($fwidth, $fheight)) { $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(wp_unslash($_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 = $path === $new_path || update_attached_file($post_id, $new_path); $meta['file'] = _wp_relative_upload_path($new_path); $size = $img->get_size(); $meta['width'] = $size['width']; $meta['height'] = $size['height']; if ($success && ('nothumb' == $target || 'all' == $target)) { $sizes = get_intermediate_image_sizes(); if ('nothumb' == $target) { $sizes = array_diff($sizes, array('thumbnail')); } } $return->fw = $meta['width']; $return->fh = $meta['height']; } elseif ('thumbnail' == $target) { $sizes = array('thumbnail'); $success = $delete = $nocrop = true; } if (isset($sizes)) { $_sizes = array(); foreach ($sizes as $size) { $tag = false; if (isset($meta['sizes'][$size])) { if (isset($backup_sizes["{$size}-orig"])) { if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes["{$size}-orig"]['file'] != $meta['sizes'][$size]['file']) { $tag = "{$size}-{$suffix}"; } } else { $tag = "{$size}-orig"; } if ($tag) { $backup_sizes[$tag] = $meta['sizes'][$size]; } } if (isset($_wp_additional_image_sizes[$size])) { $width = intval($_wp_additional_image_sizes[$size]['width']); $height = intval($_wp_additional_image_sizes[$size]['height']); $crop = $nocrop ? false : $_wp_additional_image_sizes[$size]['crop']; } else { $height = get_option("{$size}_size_h"); $width = get_option("{$size}_size_w"); $crop = $nocrop ? false : get_option("{$size}_crop"); } $_sizes[$size] = array('width' => $width, 'height' => $height, 'crop' => $crop); } $meta['sizes'] = array_merge($meta['sizes'], $img->multi_resize($_sizes)); } unset($img); if ($success) { wp_update_attachment_metadata($post_id, $meta); update_post_meta($post_id, '_wp_attachment_backup_sizes', $backup_sizes); if ($target == 'thumbnail' || $target == 'all' || $target == 'full') { // Check if it's an image edit from attachment edit screen if (!empty($_REQUEST['context']) && 'edit-attachment' == $_REQUEST['context']) { $thumb_url = wp_get_attachment_image_src($post_id, array(900, 600), true); $return->thumbnail = $thumb_url[0]; } else { $file_url = wp_get_attachment_url($post_id); if (!empty($meta['sizes']['thumbnail']) && ($thumb = $meta['sizes']['thumbnail'])) { $return->thumbnail = path_join(dirname($file_url), $thumb['file']); } else { $return->thumbnail = "{$file_url}?w=128&h=128"; } } } } else { $delete = true; } if ($delete) { wp_delete_file($new_path); } $return->msg = esc_js(__('Image saved')); return $return; }
/** * Copy an existing image file. * * @since 3.4.0 * @access private * * @param string $attachment_id Attachment ID. * @return string|false New file path on success, false on failure. */ function _copy_image_file($attachment_id) { $dst_file = $src_file = get_attached_file($attachment_id); if (!file_exists($src_file)) { $src_file = _load_image_to_edit_path($attachment_id); } if ($src_file) { $dst_file = str_replace(basename($dst_file), 'copy-' . basename($dst_file), $dst_file); $dst_file = dirname($dst_file) . '/' . wp_unique_filename(dirname($dst_file), basename($dst_file)); // The directory containing the original file may no longer exist when // using a replication plugin. wp_mkdir_p(dirname($dst_file)); if (!@copy($src_file, $dst_file)) { $dst_file = false; } } else { $dst_file = false; } return $dst_file; }
/** * Crops the image based on params passed in $_POST array */ public function cropImage() { global $_wp_additional_image_sizes; $data = $this->filterPostData(); $dst_file_url = wp_get_attachment_image_src($data['attachmentId'], $data['editedSize']); if (!$dst_file_url) { exit; } $uploadsDir = wp_upload_dir(); // checks for ssl. wp_upload_dir does not handle ssl (ssl admin trips on this and subsequent ajax success to browser) if (is_ssl()) { $uploadsDir['baseurl'] = preg_replace('#^http://#i', 'https://', $uploadsDir['baseurl']); } if (function_exists('_load_image_to_edit_path')) { // this function is consider as private, but it return proper image path. Notice it is in function_exists condition $src_file = _load_image_to_edit_path($data['attachmentId'], 'full'); $dst_file = _load_image_to_edit_path($data['attachmentId'], $data['editedSize']); } else { $src_file_url = wp_get_attachment_image_src($data['attachmentId'], 'full'); if (!$src_file_url) { echo json_encode(array('status' => 'error', 'message' => 'wrong attachment')); exit; } $src_file = str_replace($uploadsDir['baseurl'], $uploadsDir['basedir'], $src_file_url[0]); $dst_file = str_replace($uploadsDir['baseurl'], $uploadsDir['basedir'], $dst_file_url[0]); } //checks if the destination image file is present (if it's not, we want to create a new file, as the WordPress returns the original image instead of specific one) if ($dst_file == $src_file) { $attachmentData = wp_generate_attachment_metadata($data['attachmentId'], $dst_file); //overwrite with previous values $prevAttachmentData = wp_get_attachment_metadata($data['attachmentId']); if (isset($prevAttachmentData['micSelectedArea'])) { $attachmentData['micSelectedArea'] = $prevAttachmentData['micSelectedArea']; } //saves new path to the image size in the database wp_update_attachment_metadata($data['attachmentId'], $attachmentData); //new destination file path - replaces original file name with the correct one $dst_file = str_replace(basename($attachmentData['file']), $attachmentData['sizes'][$data['editedSize']]['file'], $dst_file); //retrieves the new url to file (needet to refresh the preview) $dst_file_url = wp_get_attachment_image_src($data['attachmentId'], $data['editedSize']); } //sets the destination image dimensions if (isset($_wp_additional_image_sizes[$data['editedSize']])) { $dst_w = min(intval($_wp_additional_image_sizes[$data['editedSize']]['width']), $data['select']['w'] * $data['previewScale']); $dst_h = min(intval($_wp_additional_image_sizes[$data['editedSize']]['height']), $data['select']['h'] * $data['previewScale']); } else { $dst_w = min(get_option($data['editedSize'] . '_size_w'), $data['select']['w'] * $data['previewScale']); $dst_h = min(get_option($data['editedSize'] . '_size_h'), $data['select']['h'] * $data['previewScale']); } if (!$dst_w || !$dst_h) { echo json_encode(array('status' => 'error', 'message' => 'wrong dimensions')); exit; } //prepares coordinates that will be passed to cropping function $dst_x = 0; $dst_y = 0; $src_x = max(0, $data['select']['x']) * $data['previewScale']; $src_y = max(0, $data['select']['y']) * $data['previewScale']; $src_w = max(0, $data['select']['w']) * $data['previewScale']; $src_h = max(0, $data['select']['h']) * $data['previewScale']; $size = wp_get_image_editor($src_file)->get_size(); $is_higher = $dst_h > $size["height"]; $is_wider = $dst_w > $size["width"]; if ($is_higher || $is_wider) { if ($is_higher) { $scale = $src_h / $size["height"]; } else { $scale = $src_w / $size["width"]; } $src_w = $src_w / $scale; $src_h = $src_h / $scale; $src_x = $src_x / $scale; $src_y = $src_y / $scale; } //saves the selected area $imageMetadata = wp_get_attachment_metadata($data['attachmentId']); $imageMetadata['micSelectedArea'][$data['editedSize']] = array('x' => $data['select']['x'], 'y' => $data['select']['y'], 'w' => $data['select']['w'], 'h' => $data['select']['h'], 'scale' => $data['previewScale']); wp_update_attachment_metadata($data['attachmentId'], $imageMetadata); if (function_exists('wp_get_image_editor')) { $img = wp_get_image_editor($src_file); if (!is_wp_error($img)) { $img->crop($src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, false); $img->set_quality($data['mic_quality']); $saveStatus = $img->save($dst_file); if (is_wp_error($saveStatus)) { echo json_encode(array('status' => 'error', 'message' => 'WP_ERROR: ' . $saveStatus->get_error_message())); exit; } } else { echo json_encode(array('status' => 'error', 'message' => 'WP_ERROR: ' . $img->get_error_message())); exit; } } else { //determines what's the image format $ext = pathinfo($src_file, PATHINFO_EXTENSION); if ($ext == "gif") { $src_img = imagecreatefromgif($src_file); } else { if ($ext == "png") { $src_img = imagecreatefrompng($src_file); } else { $src_img = imagecreatefromjpeg($src_file); } } if ($src_img === false) { echo json_encode(array('status' => 'error', 'message' => 'PHP ERROR: Cannot create image from the source file')); exit; } $dst_img = imagecreatetruecolor($dst_w, $dst_h); $resampleReturn = imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); if ($resampleReturn === false) { echo json_encode(array('status' => 'error', 'message' => 'PHP ERROR: imagecopyresampled')); exit; } $imageSaveReturn = true; if ($ext == "gif") { $imageSaveReturn = imagegif($dst_img, $dst_file); } else { if ($ext == "png") { $imageSaveReturn = imagepng($dst_img, $dst_file); } else { $imageSaveReturn = imagejpeg($dst_img, $dst_file, $quality); } } if ($imageSaveReturn === false) { echo json_encode(array('status' => 'error', 'message' => 'PHP ERROR: imagejpeg/imagegif/imagepng')); exit; } } // Generate Retina Image if (isset($data['make2x']) && $data['make2x'] === true) { $dst_w2x = $dst_w * 2; $dst_h2x = $dst_h * 2; $dot = strrpos($dst_file, "."); $dst_file2x = substr($dst_file, 0, $dot) . '@2x' . substr($dst_file, $dot); // Check image size and create the retina file if possible if ($src_w > $dst_w2x && $src_h > $dst_h2x) { if (function_exists('wp_get_image_editor')) { $img = wp_get_image_editor($src_file); if (!is_wp_error($img)) { $img->crop($src_x, $src_y, $src_w, $src_h, $dst_w2x, $dst_h2x, false); $img->set_quality($quality); $img->save($dst_file2x); } else { echo json_encode(array('status' => 'error', 'message' => 'WP_ERROR: ' . $img->get_error_message())); exit; } } else { $dst_img2x = imagecreatetruecolor($dst_w2x, $dst_h2x); $resampleReturn = imagecopyresampled($dst_img2x, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w2x, $dst_h2x, $src_w, $src_h); if ($resampleReturn === false) { echo json_encode(array('status' => 'error', 'message' => 'PHP ERROR: imagecopyresampled')); exit; } $imageSaveReturn = true; if ($ext == "gif") { $imageSaveReturn = imagegif($dst_img2x, $dst_file2x); } else { if ($ext == "png") { $imageSaveReturn = imagepng($dst_img2x, $dst_file2x); } else { $imageSaveReturn = imagejpeg($dst_img2x, $dst_file2x, $quality); } } if ($imageSaveReturn === false) { echo json_encode(array('status' => 'error', 'message' => 'PHP ERROR: imagejpeg/imagegif/imagepng')); exit; } } } } // update 'mic_make2x' option status to persist choice if (isset($data['make2x']) && $data['make2x'] !== get_option('mic_make2x')) { update_option('mic_make2x', $data['make2x']); } //returns the url to the generated image (to allow refreshing the preview) echo json_encode(array('status' => 'ok', 'file' => $dst_file_url[0])); exit; }
function pte_resize_images() { $logger = PteLogger::singleton(); global $pte_sizes; // Require JSON output pte_require_json(); $id = intval($_GET['id']); $w = pte_check_int($_GET['w']); $h = pte_check_int($_GET['h']); $x = pte_check_int($_GET['x']); $y = pte_check_int($_GET['y']); $save = isset($_GET['save']) && strtolower($_GET['save']) === "true"; if (pte_check_id($id) === false || $w === false || $h === false || $x === false || $y === false) { return pte_json_error("ResizeImages initialization failed: '{$id}-{$w}-{$h}-{$x}-{$y}'"); } // Check nonce if (!check_ajax_referer("pte-resize-{$id}", 'pte-nonce', false)) { return pte_json_error("CSRF Check failed"); } // Get the sizes to process $pte_sizes = $_GET['pte-sizes']; if (!is_array($pte_sizes)) { $logger->debug("Converting pte_sizes to array"); $pte_sizes = explode(",", $pte_sizes); } $sizes = pte_get_all_alternate_size_information($id); // The following information is common to all sizes // *** common-info $original_file = _load_image_to_edit_path($id); $original_size = @getimagesize($original_file); // SETS $PTE_TMP_DIR and $PTE_TMP_URL extract(pte_tmp_dir()); $thumbnails = array(); if (!$original_size) { return pte_json_error("Could not read image size"); } $logger->debug("BASE FILE DIMENSIONS/INFO: " . print_r($original_size, true)); list($orig_w, $orig_h, $orig_type) = $original_size; // *** End common-info // So this never interrupts the jpeg_quality anywhere else add_filter('jpeg_quality', 'pte_get_jpeg_quality'); add_filter('wp_editor_set_quality', 'pte_get_jpeg_quality'); foreach ($sizes as $size => $data) { // Get all the data needed to run image_create // // $dst_w, $dst_h extract(pte_get_width_height($data, $w, $h)); $logger->debug("WIDTHxHEIGHT: {$dst_w} x {$dst_h}"); // Set the cropped filename $transparent = pte_is_crop_border_enabled($w, $h, $dst_w, $dst_h) && !pte_is_crop_border_opaque(); $basename = pte_generate_filename($original_file, $dst_w, $dst_h, $transparent); $tmpfile = "{$PTE_TMP_DIR}{$id}" . DIRECTORY_SEPARATOR . "{$basename}"; // === CREATE IMAGE =================== // This function is in wp-includes/media.php // We've added a filter to return our own editor which extends the wordpress one. add_filter('wp_image_editors', 'pte_image_editors'); $editor = wp_get_image_editor($original_file); if (is_a($editor, "WP_Image_Editor_Imagick")) { $logger->debug("EDITOR: ImageMagick"); } if (is_a($editor, "WP_Image_Editor_GD")) { $logger->debug("EDITOR: GD"); } $crop_results = $editor->crop($x, $y, $w, $h, $dst_w, $dst_h); if (is_wp_error($crop_results)) { $logger->error("Error creating image: {$size}"); continue; } // The directory containing the original file may no longer exist when // using a replication plugin. wp_mkdir_p(dirname($tmpfile)); $tmpfile = dirname($tmpfile) . '/' . wp_unique_filename(dirname($tmpfile), basename($tmpfile)); $tmpurl = "{$PTE_TMP_URL}{$id}/" . basename($tmpfile); if (is_wp_error($editor->save($tmpfile))) { $logger->error("Error writing image: {$size} to '{$tmpfile}'"); continue; } // === END CREATE IMAGE =============== // URL: wp_upload_dir => base_url/subdir + /basename of $tmpfile // This is for the output $thumbnails[$size]['url'] = $tmpurl; $thumbnails[$size]['file'] = basename($tmpfile); } // Did you process anything? if (count($thumbnails) < 1) { return pte_json_error("No images processed"); } $ptenonce = wp_create_nonce("pte-{$id}"); // If save -- return pte_confirm_images if ($save) { function create_pte_confirm($thumbnail) { return $thumbnail['file']; } $_REQUEST['pte-nonce'] = $ptenonce; $_GET['pte-confirm'] = array_map('create_pte_confirm', $thumbnails); $logger->debug("CONFIRM:"); $logger->debug(print_r($_GET, true)); return pte_confirm_images(true); } return pte_json_encode(array('thumbnails' => $thumbnails, 'pte-nonce' => $ptenonce, 'pte-delete-nonce' => wp_create_nonce("pte-delete-{$id}"))); }
/** * All done page admin view * */ public static function all_done_page() { $temp_image_data = get_option('site_icon_temp_data'); if (!$temp_image_data) { // start again self::select_page(); return; } $crop_ration = $temp_image_data['large_image_data'][0] / $temp_image_data['resized_image_data'][0]; // always bigger then 1 $crop_data = self::convert_coodiantes_from_resized_to_full($_POST['crop-x'], $_POST['crop-y'], $_POST['crop-w'], $_POST['crop-h'], $crop_ration); $image_edit = wp_get_image_editor(_load_image_to_edit_path($temp_image_data['large_image_attachment_id'])); if (is_wp_error($image_edit)) { return $image_edit; } // Delete the previous site_icon $previous_site_icon_id = Jetpack_Options::get_option('site_icon_id'); self::delete_site_icon($previous_site_icon_id); // crop the image $image_edit->crop($crop_data['crop_x'], $crop_data['crop_y'], $crop_data['crop_width'], $crop_data['crop_height'], self::$min_size, self::$min_size); $dir = wp_upload_dir(); $site_icon_filename = $image_edit->generate_filename(dechex(time()) . 'v' . self::$version . '_site_icon', null, 'png'); $image_edit->save($site_icon_filename); add_filter('intermediate_image_sizes_advanced', array('Jetpack_Site_Icon', 'additional_sizes')); $site_icon_id = self::save_attachment(__('Large Blog Image', 'jetpack'), $site_icon_filename, 'image/png'); remove_filter('intermediate_image_sizes_advanced', array('Jetpack_Site_Icon', 'additional_sizes')); // Save the site_icon data into option Jetpack_Options::update_option('site_icon_id', $site_icon_id); //Get the site icon URL ready to sync Jetpack_Options::update_option('site_icon_url', jetpack_site_icon_url(get_current_blog_id(), 512)); ?> <h2 class="site-icon-title"><?php esc_html_e('Site Icon', 'jetpack'); ?> <span class="small"><?php esc_html_e('All Done', 'jetpack'); ?> </span></h2> <div id="message" class="updated below-h2"><p><?php esc_html_e('Your site icon has been uploaded!', 'jetpack'); ?> <a href="<?php echo esc_url(admin_url('options-general.php')); ?> " ><?php esc_html_e('Back to General Settings', 'jetpack'); ?> </a></p></div> <?php echo jetpack_get_site_icon(null, $size = '128'); ?> <?php echo jetpack_get_site_icon(null, $size = '48'); ?> <?php echo jetpack_get_site_icon(null, $size = '16'); ?> <?php }
function yoimg_crop_image() { $req_post = esc_html($_POST['post']); if (current_user_can('edit_post', $req_post)) { $req_size = esc_html($_POST['size']); $req_width = esc_html($_POST['width']); $req_height = esc_html($_POST['height']); $req_x = esc_html($_POST['x']); $req_y = esc_html($_POST['y']); $req_quality = esc_html($_POST['quality']); $yoimg_retina_crop_enabled = yoimg_is_retina_crop_enabled_for_size($req_size); $img_path = _load_image_to_edit_path($req_post); $attachment_metadata = wp_get_attachment_metadata($req_post); if (isset($attachment_metadata['yoimg_attachment_metadata']['crop'][$req_size]['replacement'])) { $replacement = $attachment_metadata['yoimg_attachment_metadata']['crop'][$req_size]['replacement']; } else { $replacement = null; } $has_replacement = !empty($replacement) && get_post($replacement); if ($has_replacement) { $replacement_path = _load_image_to_edit_path($replacement); $img_editor = wp_get_image_editor($replacement_path); $img_editor_retina = wp_get_image_editor($replacement_path); $full_image_attributes = wp_get_attachment_image_src($replacement, 'full'); } else { $img_editor = wp_get_image_editor($img_path); $img_editor_retina = wp_get_image_editor($img_path); $full_image_attributes = wp_get_attachment_image_src($req_post, 'full'); } if (is_wp_error($img_editor) || is_wp_error($img_editor_retina)) { return false; } $cropped_image_sizes = yoimg_get_image_sizes($req_size); $is_crop_smaller = $full_image_attributes[1] < $cropped_image_sizes['width'] || $full_image_attributes[2] < $cropped_image_sizes['height']; $crop_width = $cropped_image_sizes['width']; $crop_height = $cropped_image_sizes['height']; $img_editor->crop($req_x, $req_y, $req_width, $req_height, $crop_width, $crop_height, false); $img_editor->set_quality($req_quality); $img_path_parts = pathinfo($img_path); if (empty($attachment_metadata['sizes'][$req_size]) || empty($attachment_metadata['sizes'][$req_size]['file'])) { $cropped_image_filename = yoimg_get_cropped_image_filename($img_path_parts['filename'], $crop_width, $crop_height, $img_path_parts['extension']); $attachment_metadata['sizes'][$req_size] = array('file' => $cropped_image_filename, 'width' => $crop_width, 'height' => $crop_height, 'mime-type' => $attachment_metadata['sizes']['thumbnail']['mime-type']); } else { $cropped_image_filename = $attachment_metadata['sizes'][$req_size]['file']; } $img_editor->save($img_path_parts['dirname'] . '/' . $cropped_image_filename); if ($yoimg_retina_crop_enabled) { $crop_width_retina = $crop_width * 2; $crop_height_retina = $crop_height * 2; $is_crop_retina_smaller = $full_image_attributes[1] < $crop_width_retina || $full_image_attributes[2] < $crop_height_retina; if (!$is_crop_retina_smaller) { $img_editor_retina->crop($req_x, $req_y, $req_width, $req_height, $crop_width_retina, $crop_height_retina, false); $img_editor_retina->set_quality($req_quality); $img_retina_path_parts = pathinfo($cropped_image_filename); $cropped_image_retina_filename = $img_retina_path_parts['filename'] . '@2x.' . $img_retina_path_parts['extension']; $img_editor_retina->save($img_path_parts['dirname'] . '/' . $cropped_image_retina_filename); } } $attachment_metadata['sizes'][$req_size]['width'] = $crop_width; $attachment_metadata['sizes'][$req_size]['height'] = $crop_height; if (empty($attachment_metadata['yoimg_attachment_metadata']['crop'])) { $attachment_metadata['yoimg_attachment_metadata']['crop'] = array(); } $attachment_metadata['yoimg_attachment_metadata']['crop'][$req_size] = array('x' => $req_x, 'y' => $req_y, 'width' => $req_width, 'height' => $req_height); if ($has_replacement) { $attachment_metadata['yoimg_attachment_metadata']['crop'][$req_size]['replacement'] = $replacement; } wp_update_attachment_metadata($req_post, $attachment_metadata); status_header(200); header('Content-type: application/json; charset=UTF-8'); if ($yoimg_retina_crop_enabled) { echo json_encode(array('filename' => $cropped_image_filename, 'smaller' => $is_crop_smaller, 'retina_filename' => $cropped_image_retina_filename, 'retina_smaller' => $is_crop_retina_smaller)); } else { echo json_encode(array('filename' => $cropped_image_filename, 'smaller' => $is_crop_smaller)); } } die; }
/** * Copy an existing image file. * * @since 3.4.0 * @access private * * @param string $attachment_id Attachment ID. * @return string|false New file path on success, false on failure. */ function _copy_image_file($attachment_id) { $dst_file = $src_file = get_attached_file($attachment_id); if (!file_exists($src_file)) { $src_file = _load_image_to_edit_path($attachment_id); } if ($src_file) { $dst_file = str_replace(basename($dst_file), 'copy-' . basename($dst_file), $dst_file); $dst_file = dirname($dst_file) . '/' . wp_unique_filename(dirname($dst_file), basename($dst_file)); if (!@copy($src_file, $dst_file)) { $dst_file = false; } } else { $dst_file = false; } return $dst_file; }
function resize_image($imageData) { $rotate = isset($imageData['rotate']) && is_numeric($imageData['rotate']) ? $imageData['rotate'] : false; $resize = isset($imageData['resize']) ? $imageData['resize'] : false; $crop = isset($imageData['crop']) ? $imageData['crop'] : false; if (!$rotate && !$resize && !$crop) { return array('error' => true, 'msg' => Upfront_UimageView::_get_l10n('not_modifications')); } $image_path = isset($imageData['image_path']) ? $imageData['image_path'] : _load_image_to_edit_path($imageData['id']); $image_editor = wp_get_image_editor($image_path); if (is_wp_error($image_editor)) { return array('error' => true, 'msg' => Upfront_UimageView::_get_l10n('invalid_id')); } if ($rotate && !$image_editor->rotate(-$rotate)) { return array('error' => true, 'msg' => Upfront_UimageView::_get_l10n('edit_error')); } $full_size = $image_editor->get_size(); //Cropping for resizing allows to make the image bigger if ($resize && !$image_editor->crop(0, 0, $full_size['width'], $full_size['height'], $resize['width'], $resize['height'], false)) { return array('error' => true, 'msg' => Upfront_UimageView::_get_l10n('edit_error')); } //$cropped = array(round($crop['left']), round($crop['top']), round($crop['width']), round($crop['height'])); //Don't let the crop be bigger than the size $size = $image_editor->get_size(); $crop = array('top' => round($crop['top']), 'left' => round($crop['left']), 'width' => round($crop['width']), 'height' => round($crop['height'])); if ($crop['top'] < 0) { $crop['height'] -= $crop['top']; $crop['top'] = 0; } if ($crop['left'] < 0) { $crop['width'] -= $crop['left']; $crop['left'] = 0; } if ($size['height'] < $crop['height']) { $crop['height'] = $size['height']; } if ($size['width'] < $crop['width']) { $crop['width'] = $size['width']; } if ($crop && !$image_editor->crop($crop['left'], $crop['top'], $crop['width'], $crop['height'])) { //if($crop && !$image_editor->crop($cropped[0], $cropped[1], $cropped[2], $cropped[3])) return $this->_out(new Upfront_JsonResponse_Error(Upfront_UimageView::_get_l10n('edit_error'))); } // generate new filename $path = $image_path; $path_parts = pathinfo($path); $filename = $path_parts['filename'] . '-' . $image_editor->get_suffix(); if (!isset($imageData['skip_random_filename'])) { $filename .= '-' . rand(1000, 9999); } $imagepath = $path_parts['dirname'] . '/' . $filename . '.' . $path_parts['extension']; $image_editor->set_quality(90); $saved = $image_editor->save($imagepath); if (is_wp_error($saved)) { return array('error' => true, 'msg' => 'If images are moved from standard storage (e.g. via plugin that stores uploads to S3) Upfront does not have access. (' . implode('; ', $saved->get_error_messages()) . ')'); } if (is_wp_error($image_editor) || empty($imageData['id'])) { return array('error' => true, 'msg' => Upfront_UimageView::_get_l10n('error_save')); } $urlOriginal = wp_get_attachment_image_src($imageData['id'], 'full'); $urlOriginal = $urlOriginal[0]; $url = str_replace($path_parts['basename'], $saved['file'], $urlOriginal); if ($rotate) { //We must do a rotated version of the full size image $fullsizename = $path_parts['filename'] . '-r' . $rotate; $fullsizepath = $path_parts['dirname'] . '/' . $fullsizename . '.' . $path_parts['extension']; if (!file_exists($fullsizepath)) { $full = wp_get_image_editor(_load_image_to_edit_path($imageData['id'])); $full->rotate(-$rotate); $full->set_quality(90); $savedfull = $full->save($fullsizepath); } $urlOriginal = str_replace($path_parts['basename'], $fullsizename . '.' . $path_parts['extension'], $urlOriginal); } // We won't be cleaning up the rotated fullsize images // *** ALright, so this is the magic cleanup part // Drop the old resized image for this element, if any $used = get_post_meta($imageData['id'], 'upfront_used_image_sizes', true); $element_id = !empty($imageData['element_id']) ? $imageData['element_id'] : 0; if (!empty($used) && !empty($used[$element_id]['path']) && file_exists($used[$element_id]['path'])) { // OOOH, so we have a previos crop! @unlink($used[$element_id]['path']); // Drop the old one, we have new stuffs to replace it } $used[$element_id] = $saved; // Keep track of used elements per element ID update_post_meta($imageData['id'], 'upfront_used_image_sizes', $used); // *** Flags updated, files clear. Moving on return array('error' => false, 'url' => $url, 'urlOriginal' => $urlOriginal, 'full' => $full_size, 'crop' => $image_editor->get_size()); }
/** * Perform the actual crop */ public function performCrop() { $req_post = esc_html($_POST['post']); if (!current_user_can('edit_post', $req_post)) { json_response(['status' => 'error', 'message' => 'You are not strong enough, smart enough or fast enough.']); } $size = esc_html($_POST['size']); $crop_width = esc_html($_POST['width']); $crop_height = esc_html($_POST['height']); $crop_x = esc_html($_POST['x']); $crop_y = esc_html($_POST['y']); $img_path = _load_image_to_edit_path($req_post); $meta = wp_get_attachment_metadata($req_post); $img_editor = wp_get_image_editor($img_path); if (is_wp_error($img_editor)) { json_response(['status' => 'error', 'message' => 'Could not create image editor.']); } $crop_size = ilab_get_image_sizes($size); $dest_width = $crop_size['width']; $dest_height = $crop_size['height']; $img_editor->crop($crop_x, $crop_y, $crop_width, $crop_height, $dest_width, $dest_height, false); $img_editor->set_quality(get_option('ilab-media-crop-quality', 92)); $save_path_parts = pathinfo($img_path); $path_url = parse_url($img_path); if ($path_url !== false && isset($path_url['scheme'])) { $parsed_path = pathinfo($path_url['path']); $img_subpath = apply_filters('ilab-s3-process-file-name', $parsed_path['dirname']); $upload_dir = wp_upload_dir(); $save_path = $upload_dir['basedir'] . $img_subpath; @mkdir($save_path, 0777, true); } else { $save_path = $save_path_parts['dirname']; } $extension = $save_path_parts['extension']; $filename = preg_replace('#^(IL[0-9-]*)#', '', $save_path_parts['filename']); $filename = 'IL' . date("YmdHis") . '-' . $filename . '-' . $dest_width . 'x' . $dest_height . '.' . $extension; if (isset($meta['sizes'][$size])) { $meta['sizes'][$size]['file'] = $filename; $meta['sizes'][$size]['width'] = $dest_width; $meta['sizes'][$size]['height'] = $dest_height; $meta['sizes'][$size]['crop'] = ['x' => round($crop_x), 'y' => round($crop_y), 'w' => round($crop_width), 'h' => round($crop_height)]; } else { $meta['sizes'][$size] = array('file' => $filename, 'width' => $dest_width, 'height' => $dest_height, 'mime-type' => $meta['sizes']['thumbnail']['mime-type'], 'crop' => ['x' => round($crop_x), 'y' => round($crop_y), 'w' => round($crop_width), 'h' => round($crop_height)]); } $img_editor->save($save_path . '/' . $filename); // Let S3 upload the new crop $processedSize = apply_filters('ilab-s3-process-crop', $size, $filename, $meta['sizes'][$size]); if ($processedSize) { $meta['sizes'][$size] = $processedSize; } wp_update_attachment_metadata($req_post, $meta); $attrs = wp_get_attachment_image_src($req_post, $size); list($full_src, $full_width, $full_height, $full_cropped) = $attrs; json_response(['status' => 'ok', 'src' => $full_src, 'width' => $full_width, 'height' => $full_height]); }