Exemple #1
1
 /**
  * Creates new image size.
  *
  * @uses get_attached_file()
  * @uses image_make_intermediate_size()
  * @uses wp_update_attachment_metadata()
  * @uses get_post_meta()
  * @uses update_post_meta()
  *
  * @param $attachment_id
  * @param $width
  * @param $height
  * @param $meta
  * @param $original_src
  *
  * @return array
  */
 function themify_make_image_size($attachment_id, $width, $height, $meta, $original_src)
 {
     setlocale(LC_CTYPE, get_locale() . '.UTF-8');
     $attached_file = get_attached_file($attachment_id);
     if (apply_filters('themify_image_script_use_large_size', true) && isset($meta['sizes']['large']['file'])) {
         $attached_file = str_replace($meta['file'], trailingslashit(dirname($meta['file'])) . $meta['sizes']['large']['file'], $attached_file);
     }
     $resized = image_make_intermediate_size($attached_file, $width, $height, true);
     if ($resized && !is_wp_error($resized)) {
         // Save the new size in meta data
         $key = sprintf('resized-%dx%d', $width, $height);
         $meta['sizes'][$key] = $resized;
         $src = str_replace(basename($original_src), $resized['file'], $original_src);
         wp_update_attachment_metadata($attachment_id, $meta);
         // Save size in backup sizes so it's deleted when original attachment is deleted.
         $backup_sizes = get_post_meta($attachment_id, '_wp_attachment_backup_sizes', true);
         if (!is_array($backup_sizes)) {
             $backup_sizes = array();
         }
         $backup_sizes[$key] = $resized;
         update_post_meta($attachment_id, '_wp_attachment_backup_sizes', $backup_sizes);
         // Return resized image url, width and height.
         return array('url' => esc_url($src), 'width' => $width, 'height' => $height);
     }
     // Return resized image url, width and height.
     return array('url' => $original_src, 'width' => $width, 'height' => $height);
 }
 /** generate new image sizes for old uploads
  * 
  * @param mixed $out
  * @param int $id
  * @param string|array $size
  * @return mixed
  */
 function circleflip_make_missing_intermediate_size($out, $id, $size)
 {
     $skip_sizes = array('full', 'large', 'medium', 'thumbnail', 'thumb');
     if (is_array($size) || in_array($size, $skip_sizes)) {
         return $out;
     }
     // the size exists and the attachment doesn't have a pre-generated file of that size
     // or the intermediate size defintion changed ( during development )
     if (circleflip_intermediate_size_exists($size) && (!circleflip_image_has_intermediate_size($id, $size) || circleflip_has_intermediate_size_changed($id, $size))) {
         // get info registerd by add_image_size
         $size_info = circleflip_get_intermediate_size_info($size);
         // get path to the original file
         $file_path = get_attached_file($id);
         // resize the image
         $resized_file = image_make_intermediate_size($file_path, $size_info['width'], $size_info['height'], $size_info['crop']);
         if ($resized_file) {
             // we have a resized image, get the attachment metadata and add the new size to it
             $metadata = wp_get_attachment_metadata($id);
             $metadata['sizes'][$size] = $resized_file;
             if (wp_update_attachment_metadata($id, $metadata)) {
                 // update succeded, call image_downsize again , DRY
                 return image_downsize($id, $size);
             }
         } else {
             // failed to generate the resized image
             // call image_downsize with `full` to prevent infinit loop
             return image_downsize($id, 'full');
         }
     }
     // pre-existing intermediate size
     return $out;
 }
Exemple #3
0
 /**
  * Resizes an image to a specified size
  * @param  integer|string  $originalImage Attachment id, path or url
  * @param  integer         $width         Target width
  * @param  integer         $height        Target height
  * @param  boolean         $crop          Crop or not?
  * @return string                         Image url
  */
 public static function resize($originalImage, $width, $height, $crop = true)
 {
     $imagePath = false;
     // Image from attachment id
     if (is_numeric($originalImage)) {
         $imagePath = wp_get_attachment_url($originalImage);
     } elseif (in_array(substr($originalImage, 0, 7), array('https:/', 'http://'))) {
         $imagePath = self::urlToPath($originalImage);
     }
     if (!$imagePath) {
         return false;
     }
     $imagePath = self::removeImageSize($imagePath);
     if (!file_exists($imagePath)) {
         return false;
     }
     $imagePathInfo = pathinfo($imagePath);
     $ext = $imagePathInfo['extension'];
     $suffix = "{$width}x{$height}";
     $destPath = "{$imagePathInfo['dirname']}/{$imagePathInfo['filename']}-{$suffix}.{$ext}";
     if (file_exists($destPath)) {
         return self::pathToUrl($destPath);
     }
     if (image_make_intermediate_size($imagePath, $width, $height, $crop)) {
         return self::pathToUrl($destPath);
     }
     return $originalImage;
 }
 public function resizeImage($attachment_id, $width, $height, $crop = true)
 {
     // Get upload directory info
     $upload_info = wp_upload_dir();
     $upload_dir = $upload_info['basedir'];
     $upload_url = $upload_info['baseurl'];
     // Get file path info
     $path = get_attached_file($attachment_id);
     $path_info = pathinfo($path);
     $ext = $path_info['extension'];
     $rel_path = str_replace(array($upload_dir, ".{$ext}"), '', $path);
     $suffix = "{$width}x{$height}";
     $dest_path = "{$upload_dir}{$rel_path}-{$suffix}.{$ext}";
     $url = "{$upload_url}{$rel_path}-{$suffix}.{$ext}";
     // If file exists: do nothing
     if (file_exists($dest_path)) {
         return $url;
     }
     // Generate thumbnail
     if (image_make_intermediate_size($path, $width, $height, $crop)) {
         return $url;
     }
     // Fallback to full size
     return "{$upload_url}{$rel_path}.{$ext}";
 }
function sp_generate_attachment_metadata($attachment_id, $file)
{
    $attachment = get_post($attachment_id);
    $metadata = array();
    if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) {
        $imagesize = getimagesize($file);
        $metadata['width'] = $imagesize[0];
        $metadata['height'] = $imagesize[1];
        list($uwidth, $uheight) = wp_shrink_dimensions($metadata['width'], $metadata['height']);
        $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
        // Make the file path relative to the upload dir
        $metadata['file'] = $attachment->post_title;
        // make thumbnails and other intermediate sizes
        global $_wp_additional_image_sizes;
        $temp_sizes = array('thumbnail', 'medium', 'large');
        // Standard sizes
        if (isset($_wp_additional_image_sizes) && count($_wp_additional_image_sizes)) {
            $temp_sizes = array_merge($temp_sizes, array_keys($_wp_additional_image_sizes));
        }
        $temp_sizes = apply_filters('intermediate_image_sizes', $temp_sizes);
        foreach ($temp_sizes as $s) {
            $sizes[$s] = array('width' => '', 'height' => '', 'crop' => FALSE);
            if (isset($_wp_additional_image_sizes[$s]['width'])) {
                $sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']);
            } else {
                $sizes[$s]['width'] = get_option("{$s}_size_w");
            }
            // For default sizes set in options
            if (isset($_wp_additional_image_sizes[$s]['height'])) {
                $sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']);
            } else {
                $sizes[$s]['height'] = get_option("{$s}_size_h");
            }
            // For default sizes set in options
            if (isset($_wp_additional_image_sizes[$s]['crop'])) {
                $sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']);
            } else {
                $sizes[$s]['crop'] = get_option("{$s}_crop");
            }
            // For default sizes set in options
        }
        $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes);
        foreach ($sizes as $size => $size_data) {
            $resized = image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']);
            if ($resized) {
                $metadata['sizes'][$size] = $resized;
            }
        }
        // fetch additional metadata from exif/iptc
        $image_meta = wp_read_image_metadata($file);
        if ($image_meta) {
            $metadata['image_meta'] = $image_meta;
        }
    }
    return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id);
}
 function test_make_intermediate_size_successful()
 {
     if (!function_exists('imagejpeg')) {
         $this->markTestSkipped('jpeg support unavailable');
     }
     $image = image_make_intermediate_size(DIR_TESTDATA . '/images/a2-small.jpg', 100, 75, true);
     $this->assertInternalType('array', $image);
     $this->assertEquals(100, $image['width']);
     $this->assertEquals(75, $image['height']);
     $this->assertEquals('image/jpeg', $image['mime-type']);
     $this->assertFalse(isset($image['path']));
     unlink(DIR_TESTDATA . '/images/a2-small-100x75.jpg');
 }
 function module_file_upload()
 {
     // name of module
     $module = mgm_request_var('module', '', true);
     // file
     $file_element = 'logo_' . $module;
     // init
     $logo = array();
     // init messages
     $status = 'error';
     $message = __('Logo upload failed.', 'mgm');
     // upload check
     if (is_uploaded_file($_FILES[$file_element]['tmp_name'])) {
         // random filename
         $uniquename = substr(microtime(), 2, 8);
         // paths
         $oldname = strtolower($_FILES[$file_element]['name']);
         $newname = preg_replace('/(.*)\\.(png|jpg|jpeg|gif)$/i', $uniquename . '.$2', $oldname);
         $filepath = MGM_FILES_MODULE_DIR . $newname;
         // upload
         if (move_uploaded_file($_FILES[$file_element]['tmp_name'], $filepath)) {
             // get thumb
             $thumb = image_make_intermediate_size(MGM_FILES_MODULE_DIR . $newname, 100, 100);
             // set logo
             if ($thumb) {
                 $logo = array('image_name' => $thumb['file'], 'image_url' => MGM_FILES_MODULE_URL . $thumb['file']);
                 // remove main file, we dont need it
                 mgm_delete_file($filepath);
             } else {
                 $logo = array('image_name' => $newname, 'image_url' => MGM_FILES_MODULE_URL . $newname);
             }
             // status
             $status = 'success';
             $message = __('logo uploaded successfully, it will be attached when you update the settings.', 'mgm');
         }
     }
     // send ouput
     @ob_end_clean();
     // PRINT
     echo json_encode(array('status' => $status, 'message' => $message, 'logo' => $logo));
     // end out put
     @ob_flush();
     exit;
 }
 private function make_intermediate_image_size($source, $filename, $dest_dir, $width, $height, $crop = false, $suffix = '')
 {
     $pathinfo = awpcp_utf8_pathinfo($source);
     $safe_suffix = empty($suffix) ? '.' : "-{$suffix}.";
     $extension = $pathinfo['extension'];
     $parent_directory = $pathinfo['dirname'];
     $generated_image_name = $filename . $safe_suffix . $extension;
     $generated_image_path = implode(DIRECTORY_SEPARATOR, array($dest_dir, $generated_image_name));
     $generated_image = image_make_intermediate_size($source, $width, $height, $crop);
     if (is_array($generated_image)) {
         $temporary_image_path = implode(DIRECTORY_SEPARATOR, array($parent_directory, $generated_image['file']));
         $result = rename($temporary_image_path, $generated_image_path);
     }
     if (!isset($result) || $result === false) {
         $result = copy($source, $generated_image_path);
     }
     chmod($generated_image_path, 0644);
     return $result;
 }
 private function make_intermediate_image_size($file, $destination_dir, $width, $height, $crop = false, $suffix = '')
 {
     if (!file_exists($destination_dir) && !mkdir($destination_dir, awpcp_directory_permissions(), true)) {
         throw new AWPCP_Exception(__("Destination directory doesn't exists and couldn't be created.", 'AWPCP'));
     }
     $image = image_make_intermediate_size($file->get_path(), $width, $height, $crop);
     $safe_suffix = empty($suffix) ? '.' : "-{$suffix}.";
     $image_name = $file->get_file_name() . $safe_suffix . $file->get_extension();
     $image_path = implode(DIRECTORY_SEPARATOR, array($destination_dir, $image_name));
     if (is_array($image)) {
         $source_path = implode(DIRECTORY_SEPARATOR, array($file->get_parent_directory(), $image['file']));
         $result = rename($source_path, $image_path);
     }
     if (!isset($result) || $result === false) {
         $result = copy($file->get_path(), $image_path);
     }
     chmod($image_path, 0644);
     return $result;
 }
 /**
  * Create Image Sizes
  *
  * @since 1.1.2
  */
 function create_image_sizes($filepath)
 {
     $sizes = array();
     foreach (get_intermediate_image_sizes() as $s) {
         $sizes[$s] = array('width' => '', 'height' => '', 'crop' => true);
         $sizes[$s]['width'] = get_option("{$s}_size_w");
         // For default sizes set in options
         $sizes[$s]['height'] = get_option("{$s}_size_h");
         // For default sizes set in options
         $sizes[$s]['crop'] = get_option("{$s}_crop");
         // For default sizes set in options
     }
     // foreach()
     $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes);
     $metadata = array();
     foreach ($sizes as $size => $size_data) {
         $resized = image_make_intermediate_size($filepath, $size_data['width'], $size_data['height'], $size_data['crop']);
         if ($resized) {
             $metadata[$size] = $resized;
         }
     }
     // foreach()
     return $metadata;
 }
 function generate_featured_size($media_id)
 {
     $metadata = wp_get_attachment_metadata($media_id);
     $resized = image_make_intermediate_size(get_attached_file($media_id), $this->settings['width'], $this->settings['height'], $this->settings['crop']);
     if ($resized) {
         $metadata['sizes']['rt_media_featured_image'] = $resized;
         wp_update_attachment_metadata($media_id, $metadata);
     }
 }
Exemple #12
0
 /**
  * The downsizer. This only does something if the existing image size doesn't exist yet.
  *
  * @param	$out boolean false
  * @param	$id int Attachment ID
  * @param	$size mixed The size name, or an array containing the width & height
  * @return	mixed False if the custom downsize failed, or an array of the image if successful
  */
 function gambit_otf_regen_thumbs_media_downsize($out, $id, $size)
 {
     // Gather all the different image sizes of WP (thumbnail, medium, large) and,
     // all the theme/plugin-introduced sizes.
     global $_gambit_otf_regen_thumbs_all_image_sizes;
     if (!isset($_gambit_otf_regen_thumbs_all_image_sizes)) {
         global $_wp_additional_image_sizes;
         $_gambit_otf_regen_thumbs_all_image_sizes = array();
         $interimSizes = get_intermediate_image_sizes();
         foreach ($interimSizes as $sizeName) {
             if (in_array($sizeName, array('thumbnail', 'medium', 'large'))) {
                 $_gambit_otf_regen_thumbs_all_image_sizes[$sizeName]['width'] = get_option($sizeName . '_size_w');
                 $_gambit_otf_regen_thumbs_all_image_sizes[$sizeName]['height'] = get_option($sizeName . '_size_h');
                 $_gambit_otf_regen_thumbs_all_image_sizes[$sizeName]['crop'] = (bool) get_option($sizeName . '_crop');
             } elseif (isset($_wp_additional_image_sizes[$sizeName])) {
                 $_gambit_otf_regen_thumbs_all_image_sizes[$sizeName] = $_wp_additional_image_sizes[$sizeName];
             }
         }
     }
     // This now contains all the data that we have for all the image sizes
     $allSizes = $_gambit_otf_regen_thumbs_all_image_sizes;
     // If image size exists let WP serve it like normally
     $imagedata = wp_get_attachment_metadata($id);
     // Image attachment doesn't exist
     if (!is_array($imagedata)) {
         return false;
     }
     // If the size given is a string / a name of a size
     if (is_string($size)) {
         // If WP doesn't know about the image size name, then we can't really do any resizing of our own
         if (empty($allSizes[$size])) {
             return false;
         }
         // If the size has already been previously created, use it
         if (!empty($imagedata['sizes'][$size]) && !empty($allSizes[$size])) {
             // But only if the size remained the same
             if ($allSizes[$size]['width'] == $imagedata['sizes'][$size]['width'] && $allSizes[$size]['height'] == $imagedata['sizes'][$size]['height']) {
                 return false;
             }
             // Or if the size is different and we found out before that the size really was different
             if (!empty($imagedata['sizes'][$size]['width_query']) && !empty($imagedata['sizes'][$size]['height_query'])) {
                 if ($imagedata['sizes'][$size]['width_query'] == $allSizes[$size]['width'] && $imagedata['sizes'][$size]['height_query'] == $allSizes[$size]['height']) {
                     return false;
                 }
             }
         }
         // Resize the image
         $resized = image_make_intermediate_size(get_attached_file($id), $allSizes[$size]['width'], $allSizes[$size]['height'], $allSizes[$size]['crop']);
         // Resize somehow failed
         if (!$resized) {
             return false;
         }
         // Save the new size in WP
         $imagedata['sizes'][$size] = $resized;
         // Save some additional info so that we'll know next time whether we've resized this before
         $imagedata['sizes'][$size]['width_query'] = $allSizes[$size]['width'];
         $imagedata['sizes'][$size]['height_query'] = $allSizes[$size]['height'];
         wp_update_attachment_metadata($id, $imagedata);
         // Serve the resized image
         $att_url = wp_get_attachment_url($id);
         return array(dirname($att_url) . '/' . $resized['file'], $resized['width'], $resized['height'], true);
         // If the size given is a custom array size
     } else {
         if (is_array($size)) {
             $imagePath = get_attached_file($id);
             // This would be the path of our resized image if the dimensions existed
             $imageExt = pathinfo($imagePath, PATHINFO_EXTENSION);
             $imagePath = preg_replace('/^(.*)\\.' . $imageExt . '$/', sprintf('$1-%sx%s.%s', $size[0], $size[1], $imageExt), $imagePath);
             $att_url = wp_get_attachment_url($id);
             // If it already exists, serve it
             if (file_exists($imagePath)) {
                 return array(dirname($att_url) . '/' . basename($imagePath), $size[0], $size[1], true);
             }
             // If not, resize the image...
             $resized = image_make_intermediate_size(get_attached_file($id), $size[0], $size[1], true);
             // Resize somehow failed
             if (!$resized) {
                 return false;
             }
             // Then serve it
             return array(dirname($att_url) . '/' . $resized['file'], $resized['width'], $resized['height'], true);
         }
     }
     return false;
 }
Exemple #13
0
 /**
  * Generate post thumbnail attachment meta data.
  *
  * @since 2.1.0
  *
  * @param int $attachment_id Attachment Id to process.
  * @param string $file Filepath of the Attached image.
  *
  * @param null|array $thumbnails: thumbnails to regenerate, if null all
  *
  * @return mixed Metadata for attachment.
  */
 public static function wp_generate_attachment_metadata_custom($attachment_id, $file, $thumbnails = null)
 {
     $attachment = get_post($attachment_id);
     $meta_datas = get_post_meta($attachment_id, '_wp_attachment_metadata', true);
     $metadata = array();
     if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) {
         $imagesize = getimagesize($file);
         $metadata['width'] = $imagesize[0];
         $metadata['height'] = $imagesize[1];
         list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96);
         $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
         // Make the file path relative to the upload dir
         $metadata['file'] = _wp_relative_upload_path($file);
         // make thumbnails and other intermediate sizes
         global $_wp_additional_image_sizes;
         foreach (get_intermediate_image_sizes() as $s) {
             $sizes[$s] = array('width' => '', 'height' => '', 'crop' => false);
             if (isset($_wp_additional_image_sizes[$s]['width'])) {
                 $sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']);
             } else {
                 $sizes[$s]['width'] = get_option("{$s}_size_w");
             }
             // For default sizes set in options
             if (isset($_wp_additional_image_sizes[$s]['height'])) {
                 $sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']);
             } else {
                 $sizes[$s]['height'] = get_option("{$s}_size_h");
             }
             // For default sizes set in options
             if (isset($_wp_additional_image_sizes[$s]['crop'])) {
                 $sizes[$s]['crop'] = intval($_wp_additional_image_sizes[$s]['crop']);
             } else {
                 $sizes[$s]['crop'] = get_option("{$s}_crop");
             }
             // For default sizes set in options
         }
         $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes);
         // Only if not all sizes
         if (isset($thumbnails) && is_array($thumbnails) && isset($meta_datas['sizes']) && !empty($meta_datas['sizes'])) {
             // Fill the array with the other sizes not have to be done
             foreach ($meta_datas['sizes'] as $name => $fsize) {
                 $metadata['sizes'][$name] = $fsize;
             }
         }
         foreach ($sizes as $size => $size_data) {
             if (isset($thumbnails)) {
                 if (!in_array($size, $thumbnails)) {
                     continue;
                 }
             }
             $resized = image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']);
             if (isset($meta_datas['size'][$size])) {
                 // Remove the size from the orignal sizes for after work
                 unset($meta_datas['size'][$size]);
             }
             if ($resized) {
                 $metadata['sizes'][$size] = $resized;
             }
         }
         // fetch additional metadata from exif/iptc
         $image_meta = wp_read_image_metadata($file);
         if ($image_meta) {
             $metadata['image_meta'] = $image_meta;
         }
     }
     return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id);
 }
Exemple #14
0
 public function get_attachment_image_src($pid, $size_name = 'thumbnail', $check_dupes = true, $force_regen = false)
 {
     if ($this->p->debug->enabled) {
         $this->p->debug->args(array('pid' => $pid, 'size_name' => $size_name, 'check_dupes' => $check_dupes, 'force_regen' => $force_regen));
     }
     $size_info = $this->get_size_info($size_name);
     $img_url = '';
     $img_width = -1;
     $img_height = -1;
     $img_cropped = $size_info['crop'] === false ? 0 : 1;
     // get_size_info() returns false, true, or an array
     $ret_empty = array(null, null, null, null, null);
     if ($this->p->is_avail['media']['ngg'] === true && strpos($pid, 'ngg-') === 0) {
         if (!empty($this->p->mods['media']['ngg'])) {
             return $this->p->mods['media']['ngg']->get_image_src($pid, $size_name, $check_dupes);
         } else {
             if ($this->p->debug->enabled) {
                 $this->p->debug->log('ngg module is not available: image ID ' . $attr_value . ' ignored');
             }
             if (is_admin()) {
                 $this->p->notice->err('The NextGEN Gallery module is not available: image ID ' . $pid . ' ignored.');
             }
             return $ret_empty;
         }
     } elseif (!wp_attachment_is_image($pid)) {
         if ($this->p->debug->enabled) {
             $this->p->debug->log('exiting early: attachment ' . $pid . ' is not an image');
         }
         return $ret_empty;
     }
     if (strpos($size_name, $this->p->cf['lca'] . '-') !== false) {
         // only resize our own custom image sizes
         if (!empty($this->p->options['plugin_auto_img_resize'])) {
             // auto-resize images option must be enabled
             $img_meta = wp_get_attachment_metadata($pid);
             // does the image metadata contain our image sizes?
             if ($force_regen === true || empty($img_meta['sizes'][$size_name])) {
                 $is_accurate_width = false;
                 $is_accurate_height = false;
             } else {
                 // is the width and height in the image metadata accurate?
                 $is_accurate_width = !empty($img_meta['sizes'][$size_name]['width']) && $img_meta['sizes'][$size_name]['width'] == $size_info['width'] ? true : false;
                 $is_accurate_height = !empty($img_meta['sizes'][$size_name]['height']) && $img_meta['sizes'][$size_name]['height'] == $size_info['height'] ? true : false;
                 // if not cropped, make sure the resized image respects the original aspect ratio
                 if ($is_accurate_width && $is_accurate_height && $img_cropped === 0) {
                     if ($img_meta['width'] > $img_meta['height']) {
                         $ratio = $img_meta['width'] / $size_info['width'];
                         $check = 'height';
                     } else {
                         $ratio = $img_meta['height'] / $size_info['height'];
                         $check = 'width';
                     }
                     $should_be = (int) round($img_meta[$check] / $ratio);
                     // allow for a +/-1 pixel difference
                     if ($img_meta['sizes'][$size_name][$check] < $should_be - 1 || $img_meta['sizes'][$size_name][$check] > $should_be + 1) {
                         $is_accurate_width = false;
                         $is_accurate_height = false;
                     }
                 }
             }
             // depending on cropping, one or both sides of the image must be accurate
             // if not, attempt to create a resized image by calling image_make_intermediate_size()
             if (empty($size_info['crop']) && (!$is_accurate_width && !$is_accurate_height) || !empty($size_info['crop']) && (!$is_accurate_width || !$is_accurate_height)) {
                 if ($this->p->debug->enabled) {
                     if (empty($img_meta['sizes'][$size_name])) {
                         $this->p->debug->log($size_name . ' size not defined in the image meta');
                     } else {
                         $this->p->debug->log('image metadata (' . (empty($img_meta['sizes'][$size_name]['width']) ? 0 : $img_meta['sizes'][$size_name]['width']) . 'x' . (empty($img_meta['sizes'][$size_name]['height']) ? 0 : $img_meta['sizes'][$size_name]['height']) . ') does not match ' . $size_name . ' (' . $size_info['width'] . 'x' . $size_info['height'] . ($img_cropped === 0 ? '' : ' cropped') . ')');
                     }
                 }
                 $fullsizepath = get_attached_file($pid);
                 $resized = image_make_intermediate_size($fullsizepath, $size_info['width'], $size_info['height'], $size_info['crop']);
                 if ($this->p->debug->enabled) {
                     $this->p->debug->log('image_make_intermediate_size() reported ' . ($resized === false ? 'failure' : 'success'));
                 }
                 if ($resized !== false) {
                     $img_meta['sizes'][$size_name] = $resized;
                     wp_update_attachment_metadata($pid, $img_meta);
                 }
             }
         } elseif ($this->p->debug->enabled) {
             $this->p->debug->log('image metadata check skipped: plugin_auto_img_resize option is disabled');
         }
     }
     list($img_url, $img_width, $img_height) = apply_filters($this->p->cf['lca'] . '_image_downsize', image_downsize($pid, $size_name), $pid, $size_name);
     if ($this->p->debug->enabled) {
         $this->p->debug->log('image_downsize() = ' . $img_url . ' (' . $img_width . 'x' . $img_height . ')');
     }
     if (empty($img_url)) {
         if ($this->p->debug->enabled) {
             $this->p->debug->log('exiting early: returned image_downsize() url is empty');
         }
         return $ret_empty;
     }
     // check for resulting image dimensions that may be too small
     if (!empty($this->p->options['plugin_ignore_small_img'])) {
         $is_sufficient_width = $img_width >= $size_info['width'] ? true : false;
         $is_sufficient_height = $img_height >= $size_info['height'] ? true : false;
         if ($img_width > 0 && $img_height > 0) {
             // just in case
             $ratio = $img_width >= $img_height ? $img_width / $img_height : $img_height / $img_width;
         } else {
             $ratio = 0;
         }
         // depending on cropping, one or both sides of the image must be large enough / sufficient
         // return an empty array after showing an appropriate warning
         if (empty($size_info['crop']) && (!$is_sufficient_width && !$is_sufficient_height) || !empty($size_info['crop']) && (!$is_sufficient_width || !$is_sufficient_height)) {
             $img_meta = wp_get_attachment_metadata($pid);
             $is_too_small_text = ' is too small for the ' . $size_name . ' (' . $size_info['width'] . 'x' . $size_info['height'] . ($img_cropped === 0 ? '' : ' cropped') . ') image size';
             if (!empty($img_meta['width']) && !empty($img_meta['height']) && $img_meta['width'] < $size_info['width'] && $img_meta['height'] < $size_info['height']) {
                 $rejected_text = 'image ID ' . $pid . ' rejected - the full size image (' . $img_meta['width'] . 'x' . $img_meta['height'] . ')' . $is_too_small_text;
             } else {
                 $rejected_text = 'image ID ' . $pid . ' rejected - ' . $img_width . 'x' . $img_height . $is_too_small_text;
             }
             if ($this->p->debug->enabled) {
                 $this->p->debug->log('exiting early: ' . $rejected_text);
             }
             if (is_admin()) {
                 $this->p->notice->err('Media Library ' . $rejected_text . '. Upload a larger image or ' . $this->p->util->get_admin_url('image-dimensions', 'adjust the ' . $this->p->util->get_image_size_label($size_name) . ' social image dimensions') . '.', false, true, 'wp_' . $pid . '_' . $size_name);
             }
             return $ret_empty;
             // if this is an open graph image, make sure it is larger than 200x200
         } elseif ($size_name == $this->p->cf['lca'] . '-opengraph' && ($img_width < $this->p->cf['head']['min_img_dim'] || $img_height < $this->p->cf['head']['min_img_dim'])) {
             if ($this->p->debug->enabled) {
                 $this->p->debug->log('exiting early: image ID ' . $pid . ' rejected - ' . $img_width . 'x' . $img_height . ' is smaller than the hard-coded minimum of ' . $this->p->cf['head']['min_img_dim'] . 'x' . $this->p->cf['head']['min_img_dim']);
             }
             if (is_admin()) {
                 $this->p->notice->err('Media Library image ID ' . $pid . ' rejected - the resulting ' . $img_width . 'x' . $img_height . ' image for the ' . $this->p->util->get_admin_url('image-dimensions', $this->p->util->get_image_size_label($size_name) . ' social image dimensions') . ' is smaller than the hard-coded minimum of ' . $this->p->cf['head']['min_img_dim'] . 'x' . $this->p->cf['head']['min_img_dim'] . ' allowed by the Facebook / Open Graph standard.', false, true, 'wp_' . $pid . '_' . $size_name);
             }
             return $ret_empty;
         } elseif ($ratio >= $this->p->cf['head']['max_img_ratio']) {
             $rejected_text = 'image ID ' . $pid . ' rejected - ' . $img_width . 'x' . $img_height . ' aspect ratio is equal to / or greater than ' . $this->p->cf['head']['max_img_ratio'] . ':1';
             if ($this->p->debug->enabled) {
                 $this->p->debug->log('exiting early: ' . $rejected_text);
             }
             if (is_admin()) {
                 $this->p->notice->err('Media Library ' . $rejected_text . '. Upload a different image or ' . $this->p->util->get_admin_url('image-dimensions', 'adjust the ' . $this->p->util->get_image_size_label($size_name) . ' social image dimensions') . '.', false, true, 'wp_' . $pid . '_' . $size_name);
             }
             return $ret_empty;
         } elseif ($this->p->debug->enabled) {
             $this->p->debug->log('returned image dimensions (' . $img_width . 'x' . $img_height . ') are sufficient');
         }
     }
     if ($check_dupes == false || $this->p->util->is_uniq_url($img_url, $size_name)) {
         return array(apply_filters($this->p->cf['lca'] . '_rewrite_url', $img_url), $img_width, $img_height, $img_cropped, $pid);
     }
     return $ret_empty;
 }
Exemple #15
0
 /**
  * Takes an image URL (or attachment ID) and returns a URL to a version of that same image that is equal in dimensions to the passed $width and $height parameters
  * The image will be resized on-the-fly, saved, and returned if an image of that same size doesn't already exist in the media library
  *
  * @param string|int $image The image URL or attachment ID whose resized version the function should return
  * @param int $width The desired width of the returned image
  * @param int $height The desired height of the returned image
  * @param boolean $crop Should the image be cropped to the desired dimensions (Defaults to false in which case the image is scaled down, rather than cropped)
  * @return string
  */
 public static function thumbIt($image, $width, $height, $crop = true)
 {
     global $wpdb;
     if (is_int($image)) {
         $attachment_id = $image > 0 ? $image : false;
     } else {
         $img_url = esc_url($image);
         $upload_dir = wp_upload_dir();
         $base_url = $upload_dir['baseurl'];
         if (substr($img_url, 0, strlen($base_url)) !== $base_url) {
             return $image;
         }
         $result = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s LIMIT 1;", '%' . wpdb::esc_like(str_replace(trailingslashit($base_url), '', $img_url)) . '%'));
         $attachment_id = absint($result) > 0 ? absint($result) : false;
     }
     if ($attachment_id === false) {
         return $image;
     }
     $image = wp_get_attachment_url($attachment_id);
     $attachment_meta = wp_get_attachment_metadata($attachment_id);
     if ($attachment_meta === false) {
         return $image;
     }
     $width = absint($width);
     $height = absint($height);
     $needs_resize = true;
     foreach ($attachment_meta['sizes'] as $size) {
         if ($width === $size['width'] && $height === $size['height']) {
             $image = str_replace(basename($image), $size['file'], $image);
             $needs_resize = false;
             break;
         }
     }
     if ($needs_resize) {
         $attached_file = get_attached_file($attachment_id);
         $resized = image_make_intermediate_size($attached_file, $width, $height, (bool) $crop);
         if (!is_wp_error($resized) && $resized !== false) {
             $key = sprintf('resized-%dx%d', $width, $height);
             $attachment_meta['sizes'][$key] = $resized;
             $image = str_replace(basename($image), $resized['file'], $image);
             wp_update_attachment_metadata($attachment_id, $attachment_meta);
             $backup_sizes = get_post_meta($attachment_id, '_wp_attachment_backup_sizes', true);
             if (!is_array($backup_sizes)) {
                 $backup_sizes = array();
             }
             $backup_sizes[$key] = $resized;
             update_post_meta($attachment_id, '_wp_attachment_backup_sizes', $backup_sizes);
         }
     }
     return $image;
 }
/**
 * Generate post thumbnail attachment meta data.
 *
 * @since 2.1.0
 *
 * @param int $attachment_id Attachment Id to process.
 * @param string $file Filepath of the Attached image.
 * @return mixed Metadata for attachment.
 */
function wp_generate_attachment_metadata_custom($attachment_id, $file, $thumbnails = NULL)
{
    $attachment = get_post($attachment_id);
    $metadata = array();
    if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) {
        $imagesize = getimagesize($file);
        $metadata['width'] = $imagesize[0];
        $metadata['height'] = $imagesize[1];
        list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96);
        $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
        // Make the file path relative to the upload dir
        $metadata['file'] = _wp_relative_upload_path($file);
        $sizes = ajax_thumbnail_rebuild_get_sizes();
        $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes);
        foreach ($sizes as $size => $size_data) {
            if (isset($thumbnails) && !in_array($size, $thumbnails)) {
                $intermediate_size = image_get_intermediate_size($attachment_id, $size_data['name']);
            } else {
                $intermediate_size = image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']);
            }
            if ($intermediate_size) {
                $metadata['sizes'][$size] = $intermediate_size;
            }
        }
        // fetch additional metadata from exif/iptc
        $image_meta = wp_read_image_metadata($file);
        if ($image_meta) {
            $metadata['image_meta'] = $image_meta;
        }
    }
    return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id);
}
Exemple #17
0
function ts_media_downsize($out, $id, $size)
{
    // If image size exists let WP serve it like normally
    $imagedata = wp_get_attachment_metadata($id);
    if (!is_string($size)) {
        return false;
    }
    if (is_array($imagedata) && isset($imagedata['sizes'][$size])) {
        return false;
    }
    // Check that the requested size exists, or abort
    global $_wp_additional_image_sizes;
    if (!isset($_wp_additional_image_sizes[$size])) {
        return false;
    }
    // Make the new thumb
    if (!($resized = image_make_intermediate_size(get_attached_file($id), $_wp_additional_image_sizes[$size]['width'], $_wp_additional_image_sizes[$size]['height'], $_wp_additional_image_sizes[$size]['crop']))) {
        return false;
    }
    // Save image meta, or WP can't see that the thumb exists now
    $imagedata['sizes'][$size] = $resized;
    wp_update_attachment_metadata($id, $imagedata);
    // Return the array for displaying the resized image
    $att_url = wp_get_attachment_url($id);
    return array(dirname($att_url) . '/' . $resized['file'], $resized['width'], $resized['height'], true);
}
Exemple #18
0
function pte_get_image_data($id, $size, $size_data)
{
    $logger = PteLogger::singleton();
    $fullsizepath = get_attached_file($id);
    $path_information = image_get_intermediate_size($id, $size);
    if ($path_information && @file_exists(dirname($fullsizepath) . DIRECTORY_SEPARATOR . $path_information['file'])) {
        return $path_information;
    }
    // We don't really care how it gets generated, just that it is...
    // see ajax-thumbnail-rebuild plugin for inspiration
    if (FALSE !== $fullsizepath && @file_exists($fullsizepath)) {
        // Create the image and update the wordpress metadata
        $resized = image_make_intermediate_size($fullsizepath, $size_data['width'], $size_data['height'], $size_data['crop']);
        if ($resized) {
            $metadata = wp_get_attachment_metadata($id, true);
            $metadata['sizes'][$size] = $resized;
            wp_update_attachment_metadata($id, $metadata);
        }
    }
    // Finish how we started
    $path_information = image_get_intermediate_size($id, $size);
    if ($path_information) {
        return $path_information;
    } else {
        $logger->warn("Couldn't find or generate metadata for image: {$id}-{$size}");
    }
    return false;
}
Exemple #19
0
/**
 * Generate post image attachment meta data.
 *
 * @since 2.1.0
 *
 * @param int $attachment_id Attachment Id to process.
 * @param string $file Filepath of the Attached image.
 * @return mixed Metadata for attachment.
 */
function wp_generate_attachment_metadata($attachment_id, $file)
{
    $attachment = get_post($attachment_id);
    $metadata = array();
    if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) {
        $full_path_file = $file;
        $imagesize = getimagesize($full_path_file);
        $metadata['width'] = $imagesize[0];
        $metadata['height'] = $imagesize[1];
        list($uwidth, $uheight) = wp_shrink_dimensions($metadata['width'], $metadata['height']);
        $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
        // Make the file path relative to the upload dir
        if (($uploads = wp_upload_dir()) && false === $uploads['error']) {
            // Get upload directory
            if (0 === strpos($file, $uploads['basedir'])) {
                // Check that the upload base exists in the file path
                $file = str_replace($uploads['basedir'], '', $file);
                // Remove upload dir from the file path
                $file = ltrim($file, '/');
            }
        }
        $metadata['file'] = $file;
        // make thumbnails and other intermediate sizes
        $sizes = array('thumbnail', 'medium', 'large');
        $sizes = apply_filters('intermediate_image_sizes', $sizes);
        foreach ($sizes as $size) {
            $resized = image_make_intermediate_size($full_path_file, get_option("{$size}_size_w"), get_option("{$size}_size_h"), get_option("{$size}_crop"));
            if ($resized) {
                $metadata['sizes'][$size] = $resized;
            }
        }
        // fetch additional metadata from exif/iptc
        $image_meta = wp_read_image_metadata($full_path_file);
        if ($image_meta) {
            $metadata['image_meta'] = $image_meta;
        }
    }
    return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id);
}
Exemple #20
0
 /**
  * Generates an image size
  *
  * @param  string $size Name of the image size
  * @return array        Status for the target image size
  */
 public function generateSize($size)
 {
     // Pull remote file to local filesystem, if not available
     do_action('po_bebop_media.pull_file_to_local', $this->getPartialPath());
     // Store current file path
     $old_absolute_path = $this->getAbsolutePath($size);
     // Generate new size
     $result = image_make_intermediate_size($this->getAbsolutePath(), $this->getSizePresetWidth($size), $this->getSizePresetHeight($size), $this->getSizePresetCrop($size));
     if ($result) {
         $this->__updateWordpressMeta([$size => $result]);
         $this->__updatePluginMeta([$size => $result]);
         // Send new local file to remote filesystem
         do_action('po_bebop_media.push_file_to_remote', $this->getPartialPath($size));
         // Delete local and remote file for the target size,
         // but only if the new path is different from the old one
         if ($old_absolute_path != $this->getAbsolutePath($size)) {
             apply_filters('wp_delete_file', $old_absolute_path);
         }
         // Using the 'wp_delete_file' hook should be enough,
         // but currently it is not deleting the local file
         if ($old_absolute_path != $this->getAbsolutePath($size) && file_exists($old_absolute_path)) {
             unlink($old_absolute_path);
         }
     }
     return $this->getStatus($size);
 }
 /**
  * Parse IPTC info and move the uploaded file into the protected area
  *
  * In order to "protect" our uploaded file, we resize the original
  * file down to the largest WordPress size set in Media Settings.
  * Then we take the uploaded file and move it to the "protected area".
  * Last, we copy (rename) our resized uploaded file to be the original
  * file.
  *
  * @param $attachment_id As WordPress sees it in *postmeta table
  * "_wp_attached_file", i.e., YYYY/MM/file-name.ext
  * @since 1.0.1
  */
 public function move_image_from_attachment($attachment_id = null)
 {
     $original_file = get_attached_file($attachment_id);
     if (file_exists($original_file)) {
         $this->parse_iptc_info($original_file, $attachment_id);
         // Assign the FULL PATH to our destination file.
         $wp_upload_dir = wp_upload_dir();
         $destination_file = sell_media_get_upload_dir() . $wp_upload_dir['subdir'] . '/' . basename($original_file);
         $destination_dir = sell_media_get_upload_dir() . $wp_upload_dir['subdir'] . '/';
         // Check if the destination directory exists, i.e.
         // wp-content/uploads/sell_media/YYYY/MM if not we create it.
         if (!file_exists(dirname($destination_file))) {
             wp_mkdir_p(dirname($destination_file));
         }
         /**
          * Resize original file down to the largest size set in the Media Settings
          *
          * Determine which version of WP we are using.
          * Would rather check if the correct function exists
          * but the function 'image_make_intermediate_size' uses other
          * functions that are in trunk and not in 3.4
          */
         global $wp_version;
         if (version_compare($wp_version, '3.5', '>=')) {
             /**
              * Resize the "original" to our largest size set in the Media Settings.
              *
              * This creates a file named filename-[width]x[height].jpg
              * From here the "original" file is still in our uploads dir, its needed to create
              * the additional image sizes. Once we're done making the additional sizes, we rename
              * the filename-[width]x[height].jpg to filename.jpg, thus having a resized "original"
              * file.
              */
             $image_new_size = image_make_intermediate_size($original_file, get_option('large_size_w'), get_option('large_size_h'), false);
             /**
              * If for some reason the image resize fails we just fall back to the original image.
              * Example, the image the user is trying to sell is smaller than our "max width".
              */
             if (empty($image_new_size)) {
                 $resized_image = $original_file;
                 $keep_original = true;
             } else {
                 $keep_original = false;
                 $resized_image = $wp_upload_dir['path'] . '/' . $image_new_size['file'];
             }
             if (!file_exists($destination_file)) {
                 /**
                  * Move our originally upload file into the protected area
                  */
                 copy($original_file, $destination_file);
                 if (!$keep_original) {
                     unlink($original_file);
                 }
                 /**
                  * We rename our resize original file i.e., "filename-[width]x[height].jpg" located in our uploads directory
                  * to "filename.jpg"
                  */
                 $new_path_source = dirname($original_file) . '/' . basename($resized_image);
                 $new_path_destination = $original_file;
                 copy($new_path_source, $new_path_destination);
             }
         } else {
             $resized_image = image_resize($original_file, get_option('large_size_w'), get_option('large_size_h'), false, null, $wp_upload_dir['path'], 90);
             if (!file_exists($destination_file)) {
                 // Copy original to our protected area
                 @copy($original_file, $destination_file);
                 // Copy (rename) our resized image to the original
                 @copy($resized_image, dirname($resized_image) . '/' . basename($original_file));
             }
         }
     }
 }
 /**
  * Save image on wp_upload_dir
  * Add image to the media library and attach in the post
  *
  * @param string $url image url
  * @param int $post_id
  * @return string new image url
  */
 public function save_image($url, $post_id = 0)
 {
     if (!function_exists('curl_init')) {
         return;
     }
     setlocale(LC_ALL, "en_US.UTF8");
     $agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_USERAGENT, $agent);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
     $image_data = curl_exec($ch);
     if ($image_data === false) {
         return;
     }
     $image_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
     if (strpos($image_type, 'image') === false) {
         return;
     }
     $image_size = curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
     $image_file_name = basename($url);
     $image_name = $this->get_image_custom_name($image_file_name);
     $upload_dir = wp_upload_dir(date('Y/m'));
     $image_path = urldecode($upload_dir['path'] . '/' . $image_name);
     $image_url = urldecode($upload_dir['url'] . '/' . $image_name);
     // check if file with same name exists in upload path, rename file
     while (file_exists($image_path)) {
         if ($image_size == filesize($image_path)) {
             return $image_url;
         } else {
             $num = rand(1, 99);
             $image_path = urldecode($upload_dir['path'] . '/' . $num . '_' . $image_name);
             $image_url = urldecode($upload_dir['url'] . '/' . $num . '_' . $image_name);
         }
     }
     curl_close($ch);
     file_put_contents($image_path, $image_data);
     // if set max width and height resize image
     if (isset($this->options['max_width']) && $this->options['max_width'] || isset($this->options['max_height']) && $this->options['max_height']) {
         $width = isset($this->options['max_width']) ? $this->options['max_width'] : null;
         $height = isset($this->options['max_height']) ? $this->options['max_height'] : null;
         $image_resized = image_make_intermediate_size($image_path, $width, $height);
         $image_url = urldecode($upload_dir['url'] . '/' . $image_resized['file']);
     }
     $attachment = array('guid' => $image_url, 'post_mime_type' => $image_type, 'post_title' => preg_replace('/\\.[^.]+$/', '', $image_name), 'post_content' => '', 'post_status' => 'inherit');
     $attach_id = wp_insert_attachment($attachment, $image_path, $post_id);
     $attach_data = wp_generate_attachment_metadata($attach_id, $image_path);
     wp_update_attachment_metadata($attach_id, $attach_data);
     return $image_url;
 }
/**
 * wpmlm scale image function, dynamically resizes an image oif no image already exists of that size.
 */
function wpmlm_scale_image()
{
    global $wpdb;
    if (!isset($_REQUEST['wpmlm_action']) || !isset($_REQUEST['attachment_id']) || 'scale_image' != $_REQUEST['wpmlm_action'] || !is_numeric($_REQUEST['attachment_id'])) {
        return false;
    }
    require_once ABSPATH . 'wp-admin/includes/image.php';
    $attachment_id = absint($_REQUEST['attachment_id']);
    $width = absint($_REQUEST['width']);
    $height = absint($_REQUEST['height']);
    $intermediate_size = '';
    if ($width >= 10 && $height >= 10 && ($width <= 1024 && $height <= 1024)) {
        $intermediate_size = "wpmlm-{$width}x{$height}";
        $generate_thumbnail = true;
    } else {
        if (isset($_REQUEST['intermediate_size'])) {
            $intermediate_size = esc_attr($_REQUEST['intermediate_size']);
        }
        $generate_thumbnail = false;
    }
    // If the attachment ID is greater than 0, and the width and height is greater than or equal to 10, and less than or equal to 1024
    if ($attachment_id > 0 && $intermediate_size != '') {
        // Get all the required information about the attachment
        $uploads = wp_upload_dir();
        $image_meta = get_post_meta($attachment_id, '');
        $file_path = get_attached_file($attachment_id);
        foreach ($image_meta as $meta_name => $meta_value) {
            // clean up the meta array
            $image_meta[$meta_name] = maybe_unserialize(array_pop($meta_value));
        }
        if (!isset($image_meta['_wp_attachment_metadata'])) {
            $image_meta['_wp_attachment_metadata'] = '';
        }
        $attachment_metadata = $image_meta['_wp_attachment_metadata'];
        if (!isset($attachment_metadata['sizes'])) {
            $attachment_metadata['sizes'] = '';
        }
        if (!isset($attachment_metadata['sizes'][$intermediate_size])) {
            $attachment_metadata['sizes'][$intermediate_size] = '';
        }
        // determine if we already have an image of this size
        if (count($attachment_metadata['sizes']) > 0 && $attachment_metadata['sizes'][$intermediate_size]) {
            $intermediate_image_data = image_get_intermediate_size($attachment_id, $intermediate_size);
            if (file_exists($file_path)) {
                $original_modification_time = filemtime($file_path);
                $cache_modification_time = filemtime($uploads['basedir'] . "/" . $intermediate_image_data['path']);
                if ($original_modification_time < $cache_modification_time) {
                    $generate_thumbnail = false;
                }
            }
        }
        if ($generate_thumbnail == true) {
            //JS - 7.1.2010 - Added true parameter to function to not crop - causing issues on WPShop
            $intermediate_size_data = image_make_intermediate_size($file_path, $width, $height, true);
            $attachment_metadata['sizes'][$intermediate_size] = $intermediate_size_data;
            wp_update_attachment_metadata($attachment_id, $attachment_metadata);
            $intermediate_image_data = image_get_intermediate_size($attachment_id, $intermediate_size);
        }
        /// if we are serving the page using SSL, we have to use for the image too.
        if (is_ssl()) {
            $output_url = str_replace("http://", "https://", $intermediate_image_data['url']);
        } else {
            $output_url = $intermediate_image_data['url'];
        }
        wp_redirect($output_url);
    } else {
        _e("Invalid Image parameters", 'wpmlm');
    }
    exit;
}
 /**
  * Builds the image
  * @uses     image_make_intermediate_size
  * @internal param array $atts
  * @return   mixed string/WP Error $html
  */
 public function getImage()
 {
     $atts = $this->getAttributes();
     $atts = $this->parseAttributes($atts);
     $atts = $this->sanitizeAttributes($atts);
     $this->setHeightWidthString($atts['width'], $atts['height']);
     $hw_string = $this->getHeightWidthString();
     !$atts['hwmarkup'] and $hw_string = '';
     $needs_resize = true;
     $file = 'No image';
     $error = false;
     // ID as src
     if (is_int($atts['src'])) {
         $att_id = $atts['src'];
         // returns false on failure
         $atts['src'] = wp_get_attachment_url($att_id);
         // If nothing was found:
         !$atts['src'] and $error = true;
     } else {
         // Let's see if the image belongs to our uploads directory…
         $img_url = substr($atts['src'], 0, strlen($this->getBaseUrl()));
         // …And if not: just return the image HTML string
         if ($img_url !== $this->getBaseUrl()) {
             return $this->getMarkUp($img_url, $hw_string, $atts['classes']);
         }
         // Prepare file name for DB search.
         $file = str_replace(trailingslashit($this->getBaseUrl()), '', $atts['src']);
         // Look up the file in the database.
         $att_id = $this->getAttachment($file);
         // If no attachment record was found: Prepare for an WP_Error.
         !$att_id and $error = true;
     }
     // Abort if the attachment wasn't found
     if ($error) {
         return new WP_Error('no_attachment', __('Attachment not found by the dynamic-image shortcode.', 'dyn_textdomain'), $file);
     }
     // Look through the attachment meta data for an image that fits our size.
     $meta = wp_get_attachment_metadata($att_id);
     $this->setAttachmentMeta($meta);
     foreach ($meta['sizes'] as $size) {
         if ($atts['width'] === $size['width'] and $atts['height'] === $size['height']) {
             $atts['src'] = str_replace(basename($atts['src']), $size['file'], $atts['src']);
             $needs_resize = false;
             // We found an image. Now abort the loop and process it.
             break;
         }
     }
     // If we need resizing
     if ($needs_resize) {
         // and if an image of such size was not found,…
         $attached_file = get_attached_file($att_id);
         // …we can create one.
         $resized = image_make_intermediate_size($attached_file, $atts['width'], $atts['height'], true);
         if (!is_wp_error($resized) and false !== $resized) {
             // Generate key for new size
             $key = sprintf('resized-%dx%d', $atts['width'], $atts['height']);
             // Push to Meta Data Array
             $meta['sizes'][$key] = $resized;
             // Update src for final MarkUp
             $atts['src'] = str_replace(basename($atts['src']), $resized['file'], $atts['src']);
             // Let metadata know about our new size.
             wp_update_attachment_metadata($att_id, $meta);
             // Record in backup sizes, so everything's
             // cleaned up when attachment is deleted.
             $backup_sizes = get_post_meta($att_id, '_wp_attachment_backup_sizes', true);
             #
             // If an error occurred, we'll get back FALSE
             // By default it's not a single meta entry, so we
             // should get an array anyway. Unless WP_Cache went off.
             !is_array($backup_sizes) and $backup_sizes = array();
             // Add the new image to the size meta data array.
             $backup_sizes[$key] = $resized;
             // Update the meta entry.
             update_post_meta($att_id, '_wp_attachment_backup_sizes', $backup_sizes);
         }
     }
     // Generate the markup and return:
     $html = $this->getMarkUp($atts['src'], $hw_string, $atts['classes']);
     return $html;
 }
function wp_save_image($post_id)
{
    $return = new stdClass();
    $success = $delete = $scaled = $nocrop = false;
    $post = get_post($post_id);
    @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
    $img = load_image_to_edit($post_id, $post->post_mime_type);
    if (!is_resource($img)) {
        $return->error = esc_js(__('Unable to create new image.'));
        return $return;
    }
    $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
    $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
    $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
    $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
    if ($scale && $fwidth > 0 && $fheight > 0) {
        $sX = imagesx($img);
        $sY = imagesy($img);
        // check if it has roughly the same w / h ratio
        $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
        if (-0.1 < $diff && $diff < 0.1) {
            // scale the full size image
            $dst = wp_imagecreatetruecolor($fwidth, $fheight);
            if (imagecopyresampled($dst, $img, 0, 0, 0, 0, $fwidth, $fheight, $sX, $sY)) {
                imagedestroy($img);
                $img = $dst;
                $scaled = true;
            }
        }
        if (!$scaled) {
            $return->error = esc_js(__('Error while saving the scaled image. Please reload the page and try again.'));
            return $return;
        }
    } elseif (!empty($_REQUEST['history'])) {
        $changes = json_decode(stripslashes($_REQUEST['history']));
        if ($changes) {
            $img = image_edit_apply_changes($img, $changes);
        }
    } else {
        $return->error = esc_js(__('Nothing to save, the image has not changed.'));
        return $return;
    }
    $meta = wp_get_attachment_metadata($post_id);
    $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true);
    if (!is_array($meta)) {
        $return->error = esc_js(__('Image data does not exist. Please re-upload the image.'));
        return $return;
    }
    if (!is_array($backup_sizes)) {
        $backup_sizes = array();
    }
    // generate new filename
    $path = get_attached_file($post_id);
    $path_parts = pathinfo($path);
    $filename = $path_parts['filename'];
    $suffix = time() . rand(100, 999);
    if (defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) {
        if ('thumbnail' == $target) {
            $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}";
        } else {
            $new_path = $path;
        }
    } else {
        while (true) {
            $filename = preg_replace('/-e([0-9]+)$/', '', $filename);
            $filename .= "-e{$suffix}";
            $new_filename = "{$filename}.{$path_parts['extension']}";
            $new_path = "{$path_parts['dirname']}/{$new_filename}";
            if (file_exists($new_path)) {
                $suffix++;
            } else {
                break;
            }
        }
    }
    // save the full-size file, also needed to create sub-sizes
    if (!wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id)) {
        $return->error = esc_js(__('Unable to save the image.'));
        return $return;
    }
    if ('nothumb' == $target || 'all' == $target || 'full' == $target || $scaled) {
        $tag = false;
        if (isset($backup_sizes['full-orig'])) {
            if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) {
                $tag = "full-{$suffix}";
            }
        } else {
            $tag = 'full-orig';
        }
        if ($tag) {
            $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']);
        }
        $success = update_attached_file($post_id, $new_path);
        $meta['file'] = _wp_relative_upload_path($new_path);
        $meta['width'] = imagesx($img);
        $meta['height'] = imagesy($img);
        list($uwidth, $uheight) = wp_constrain_dimensions($meta['width'], $meta['height'], 128, 96);
        $meta['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
        if ($success && ('nothumb' == $target || 'all' == $target)) {
            $sizes = get_intermediate_image_sizes();
            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)) {
        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];
                }
            }
            $crop = $nocrop ? false : get_option("{$size}_crop");
            $resized = image_make_intermediate_size($new_path, get_option("{$size}_size_w"), get_option("{$size}_size_h"), $crop);
            if ($resized) {
                $meta['sizes'][$size] = $resized;
            } else {
                unset($meta['sizes'][$size]);
            }
        }
    }
    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') {
            $file_url = wp_get_attachment_url($post_id);
            if ($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) {
        $delpath = apply_filters('wp_delete_file', $new_path);
        @unlink($delpath);
    }
    imagedestroy($img);
    $return->msg = esc_js(__('Image saved'));
    return $return;
}
 /**
  * Reads the taxonomy and returns the URL to the taxonomy term icon.
  *
  * @since 1.0.0
  * @param none
  * @return none
  */
 function get_category_term_icon_src($term_id, $size)
 {
     if (isset($this->opts['icons_category'][$term_id]) && intval($this->opts['icons_category'][$term_id])) {
         $icon_image_id = $this->opts['icons_category'][$term_id];
         $icon_image_src = wp_get_attachment_image_src($icon_image_id, array($size, $size));
         if ($icon_image_src) {
             return $icon_image_src[0];
         }
     } else {
         if (isset($this->opts['categories']['default_icon_id']) && intval($this->opts['categories']['default_icon_id'])) {
             $default_icon_id = $this->opts['categories']['default_icon_id'];
             $icon_image_src = wp_get_attachment_image_src($default_icon_id, array($size, $size), true);
             if (!is_wp_error($icon_image_src) && $icon_image_src !== false) {
                 if ($icon_image_src && isset($icon_image_src[0]) && strlen($icon_image_src[0])) {
                     return $icon_image_src[0];
                 }
             }
         } else {
             $icon_image_path = $this->get_default_category_icon_path();
             $icon_image_src = image_make_intermediate_size($icon_image_path, $size, $size, true);
             if (!is_wp_error($icon_image_src) && $icon_image_src !== false) {
                 if ($icon_image_src && isset($icon_image_src['file'])) {
                     return dirname($this->get_default_category_icon_url()) . "/" . $icon_image_src['file'];
                 }
             }
         }
     }
     if (isset($icon_image_path) && strlen($icon_image_path)) {
         return dirname($this->get_default_category_icon_url()) . "/" . basename($icon_image_path);
     }
 }
Exemple #27
0
        public function get_attachment_image_src($pid, $size_name = 'thumbnail', $check_dupes = true)
        {
            $this->p->debug->args(array('pid' => $pid, 'size_name' => $size_name, 'check_dupes' => $check_dupes));
            $size_info = $this->get_size_info($size_name);
            $img_url = '';
            $img_width = -1;
            $img_height = -1;
            $img_cropped = empty($size_info['crop']) ? 0 : 1;
            $ret_empty = array(null, null, null, null);
            if ($this->p->is_avail['media']['ngg'] === true && strpos($pid, 'ngg-') === 0) {
                if (!empty($this->p->addons['media']['ngg'])) {
                    return $this->p->addons['media']['ngg']->get_image_src($pid, $size_name, $check_dupes);
                } else {
                    if (is_admin()) {
                        $this->p->notice->err('The NextGEN Gallery addon is not available: image id ' . $pid . ' ignored.');
                    } else {
                        $this->p->debug->log('ngg addon is not available: image id ' . $attr_value . ' ignored');
                    }
                    return $ret_empty;
                }
            } elseif (!wp_attachment_is_image($pid)) {
                $this->p->debug->log('exiting early: attachment ' . $pid . ' is not an image');
                return $ret_empty;
            }
            if (strpos($size_name, $this->p->cf['lca'] . '-') !== false) {
                // only resize our own custom image sizes
                if (!empty($this->p->options['plugin_auto_img_resize'])) {
                    // 'Auto-Resize Images' option must be enabled
                    $img_meta = wp_get_attachment_metadata($pid);
                    if (empty($img_meta['sizes'][$size_name])) {
                        // does the image metadata contain our image sizes?
                        $is_accurate_width = false;
                        $is_accurate_height = false;
                    } else {
                        // is the width and height in the image metadata accurate?
                        $is_accurate_width = !empty($img_meta['sizes'][$size_name]['width']) && $img_meta['sizes'][$size_name]['width'] == $size_info['width'] ? true : false;
                        $is_accurate_height = !empty($img_meta['sizes'][$size_name]['height']) && $img_meta['sizes'][$size_name]['height'] == $size_info['height'] ? true : false;
                        // if not cropped, make sure the resized image respects the original aspect ratio
                        if ($is_accurate_width && $is_accurate_height && empty($size_info['crop'])) {
                            if ($img_meta['width'] > $img_meta['height']) {
                                $ratio = $img_meta['width'] / $size_info['width'];
                                $check = 'height';
                            } else {
                                $ratio = $img_meta['height'] / $size_info['height'];
                                $check = 'width';
                            }
                            $should_be = (int) round($img_meta[$check] / $ratio);
                            // allow for a +/-1 pixel difference
                            if ($img_meta['sizes'][$size_name][$check] < $should_be - 1 || $img_meta['sizes'][$size_name][$check] > $should_be + 1) {
                                $is_accurate_width = false;
                                $is_accurate_height = false;
                            }
                        }
                    }
                    // depending on cropping, one or both sides of the image must be accurate
                    // if not, attempt to create a resized image by calling image_make_intermediate_size()
                    if (empty($size_info['crop']) && (!$is_accurate_width && !$is_accurate_height) || !empty($size_info['crop']) && (!$is_accurate_width || !$is_accurate_height)) {
                        if ($this->p->debug->is_on()) {
                            if (empty($img_meta['sizes'][$size_name])) {
                                $this->p->debug->log($size_name . ' size not defined in the image meta');
                            } else {
                                $this->p->debug->log('image metadata (' . (empty($img_meta['sizes'][$size_name]['width']) ? 0 : $img_meta['sizes'][$size_name]['width']) . 'x' . (empty($img_meta['sizes'][$size_name]['height']) ? 0 : $img_meta['sizes'][$size_name]['height']) . ') does not match ' . $size_name . ' (' . $size_info['width'] . 'x' . $size_info['height'] . (empty($size_info['crop']) ? '' : ' cropped') . ')');
                            }
                        }
                        $fullsizepath = get_attached_file($pid);
                        $resized = image_make_intermediate_size($fullsizepath, $size_info['width'], $size_info['height'], $size_info['crop']);
                        $this->p->debug->log('image_make_intermediate_size() reported ' . ($resized === false ? 'failure' : 'success'));
                        if ($resized !== false) {
                            $img_meta['sizes'][$size_name] = $resized;
                            wp_update_attachment_metadata($pid, $img_meta);
                        }
                    }
                } else {
                    $this->p->debug->log('image metadata check skipped: plugin_auto_img_resize option is disabled');
                }
            }
            list($img_url, $img_width, $img_height) = apply_filters($this->p->cf['lca'] . '_image_downsize', image_downsize($pid, $size_name), $pid, $size_name);
            $this->p->debug->log('image_downsize() = ' . $img_url . ' (' . $img_width . 'x' . $img_height . ')');
            if (empty($img_url)) {
                $this->p->debug->log('exiting early: returned image_downsize() url is empty');
                return $ret_empty;
            }
            // check for resulting image dimenions that may be too small
            if (!empty($this->p->options['plugin_ignore_small_img'])) {
                $is_sufficient_width = $img_width >= $size_info['width'] ? true : false;
                $is_sufficient_height = $img_height >= $size_info['height'] ? true : false;
                // depending on cropping, one or both sides of the image must be large enough / sufficient
                // return an empty array after showing an appropriate warning
                if (empty($size_info['crop']) && (!$is_sufficient_width && !$is_sufficient_height) || !empty($size_info['crop']) && (!$is_sufficient_width || !$is_sufficient_height)) {
                    $size_too_small_text = ' too small for ' . $size_name . ' dimensions (' . $size_info['width'] . 'x' . $size_info['height'] . (empty($size_info['crop']) ? '' : ' cropped') . ')';
                    $img_meta = wp_get_attachment_metadata($pid);
                    if (!empty($img_meta['width']) && !empty($img_meta['height']) && $img_meta['width'] < $size_info['width'] && $img_meta['height'] < $size_info['height']) {
                        $rejected_text = 'image id ' . $pid . ' rejected - original image ' . $img_meta['width'] . 'x' . $img_meta['height'] . $size_too_small_text;
                    } else {
                        $rejected_text = 'image id ' . $pid . ' rejected - ' . $img_width . 'x' . $img_height . $size_too_small_text;
                    }
                    $this->p->debug->log('exiting early: ' . $rejected_text);
                    if (is_admin()) {
                        $this->p->notice->err('Media Library ' . $rejected_text . '.
							Upload a larger image, or adjust the ' . $size_name . ' image dimensions setting.', false, true, 'dim_wp_' . $pid);
                    }
                    return $ret_empty;
                } else {
                    $this->p->debug->log('returned image dimensions (' . $img_width . 'x' . $img_height . ') are sufficient');
                }
            }
            if ($check_dupes == false || $this->p->util->is_uniq_url($img_url)) {
                return array(apply_filters($this->p->cf['lca'] . '_rewrite_url', $img_url), $img_width, $img_height, $img_cropped);
            }
            return $ret_empty;
        }
Exemple #28
0
function op_upload_file($name)
{
    $uploads = wp_upload_dir();
    $fileobj = is_array($name) ? $name : $_FILES[$name];
    if (!empty($fileobj['tmp_name']) && file_is_displayable_image($fileobj['tmp_name'])) {
        if ($file = wp_handle_upload($fileobj, array('test_form' => false, 'action' => 'wp_handle_upload'))) {
            $sizes = array();
            if (isset($field['field_opts'])) {
                $opts = $field['field_opts'];
                if (isset($opts['max_w']) && isset($opts['max_h'])) {
                    $sizes = array($opts['max_w'], $opts['max_h']);
                }
            }
            $image_url = $file['url'];
            if (count($sizes) == 2) {
                $resized = image_make_intermediate_size($file['file'], $sizes[0], $sizes[1]);
                if ($resized) {
                    $image_url = $uploads['url'] . '/' . $resized['file'];
                }
            }
            $attachment = array('post_title' => $fileobj['name'], 'post_content' => '', 'post_status' => 'inherit', 'post_mime_type' => $file['type'], 'guid' => $image_url);
            $aid = wp_insert_attachment($attachment, $file['file'], 0);
            if (!is_wp_error($aid)) {
                wp_update_attachment_metadata($aid, wp_generate_attachment_metadata($aid, $file['file']));
                return array('image' => $image_url);
            } else {
                return array('error' => $aid->get_error_message());
            }
        }
    } else {
        return array('error' => $fileobj['error'] == 4 ? false : __('The file you tried to upload is not a valid image.', OP_SN));
    }
}
 static function createWatermarkImage($source_dir, $destination_dir, $file_name, $delete_existing_file = false, $watermark_text = '', $args = array())
 {
     global $wp_photo_gallery;
     if ($watermark_text === '') {
         $watermark_text = ' ';
         //get_site_url();
     }
     $watermark_image_name = 'watermark_' . $file_name;
     $dest = $destination_dir . $watermark_image_name;
     if (file_exists($dest)) {
         if ($delete_existing_file === false) {
             return;
         }
     }
     $sourch_file = $source_dir . $file_name;
     $image_info = getimagesize($sourch_file);
     list($width, $height) = $image_info;
     $mime_type = strtolower($image_info['mime']);
     $desired_height = isset($args['watermark_height']) ? $args['watermark_height'] : '';
     $desired_width = isset($args['watermark_width']) ? $args['watermark_width'] : '';
     $font_size = isset($args['watermark_font_size']) ? $args['watermark_font_size'] : '';
     $watermark_placement = isset($args['watermark_placement']) ? $args['watermark_placement'] : '0';
     $watermark_opacity = isset($args['watermark_opacity']) ? $args['watermark_opacity'] : '35';
     //$watermark_colour = isset($args['watermark_colour'])?$args['watermark_colour']:'ffffff'; //TODO - introduce in settings using a colour picker
     if ($desired_height != '') {
         //we have a portrait image so use the height as the maximum dimension
         if ($desired_height > $height) {
             $desired_height = $height;
         }
         //Check to make sure the watermarked image is not larger than the original
         $desired_width = floor($width * ($desired_height / $height));
     } else {
         //we have a landscape image so use the width as the maximum dimension
         if (empty($desired_width)) {
             $desired_width = 600;
         }
         if ($desired_width > $width) {
             $desired_width = $width;
         }
         //Check to make sure the watermarked image is not larger than the original
         $desired_height = floor($height * ($desired_width / $width));
     }
     if (empty($font_size)) {
         $font_size = 35;
     }
     if ($mime_type == 'image/jpeg' || $mime_type == 'image/pjpeg') {
         $image = imagecreatefromjpeg($sourch_file);
     } else {
         if ($mime_type == 'image/png') {
             $image = imagecreatefrompng($sourch_file);
         }
     }
     $font = WP_PHOTO_PATH . '/fonts' . DIRECTORY_SEPARATOR . 'arial.ttf';
     $TextSize = ImageTTFBBox($font_size, 0, $font, $watermark_text) or die;
     $TextWidth = abs($TextSize[2]) + abs($TextSize[0]) + 8;
     //Added an extra 8 pixels because otherwise the watermark text appeared slightly cut-off on the RHS
     $TextHeight = abs($TextSize[7]) + abs($TextSize[1]);
     // Create Image for Text
     $image_p = ImageCreateTrueColor($TextWidth, $TextHeight);
     ImageSaveAlpha($image_p, true);
     ImageAlphaBlending($image_p, false);
     $bgText = imagecolorallocatealpha($image_p, 255, 255, 255, 127);
     imagefill($image_p, 0, 0, $bgText);
     $watermark_transparency = 127 - $watermark_opacity * 1.27;
     $color = 'ffffff';
     //TODO - introduce in settings using a colour picker
     $rgb = WPPGPhotoGallery::hex2rgb($color, false);
     $TextColor = imagecolorallocatealpha($image_p, $rgb[0], $rgb[1], $rgb[2], $watermark_transparency);
     // Create Text on image
     imagettftext($image_p, $font_size, 0, 0, abs($TextSize[5]), $TextColor, $font, $watermark_text);
     $watermark_img_path = $image_p;
     imagealphablending($image_p, false);
     imagesavealpha($image_p, true);
     $sourcefile_width = imageSX($image);
     $sourcefile_height = imageSY($image);
     $watermarkfile_width = imageSX($image_p);
     $watermarkfile_height = imageSY($image_p);
     if ($watermark_placement == '0') {
         //Centre
         $dest_x = $sourcefile_width / 2 - $watermarkfile_width / 2;
         $dest_y = $sourcefile_height / 2 - $watermarkfile_height / 2;
     } elseif ($watermark_placement == '1') {
         //Top Left
         $dest_x = 5;
         $dest_y = 5;
     } elseif ($watermark_placement == '2') {
         //Top Right
         $dest_x = $sourcefile_width - $watermarkfile_width - 5;
         $dest_y = 5;
     } elseif ($watermark_placement == '3') {
         //Bottom Right
         $dest_x = $sourcefile_width - $watermarkfile_width - 5;
         $dest_y = $sourcefile_height - $watermarkfile_height - 5;
     } elseif ($watermark_placement == '4') {
         //Bottom Left
         $dest_x = 5;
         $dest_y = $sourcefile_height - $watermarkfile_height - 5;
     } else {
         //default - Centre
         $dest_x = $sourcefile_width / 2 - $watermarkfile_width / 2;
         $dest_y = $sourcefile_height / 2 - $watermarkfile_height / 2;
     }
     if ($watermark_placement != '5') {
         //Place the image according to the co-ordinates calculated from above
         imagecopy($image, $image_p, $dest_x, $dest_y, 0, 0, $watermarkfile_width, $watermarkfile_height);
     } else {
         //Display watermark text as repeated grid
         $top = 20;
         while ($top < $sourcefile_height) {
             $left = 10;
             while ($left < $sourcefile_width) {
                 imagecopy($image, $image_p, $left, $top, 0, 0, $TextWidth, $TextHeight);
                 $left = $left + $TextWidth + 50;
             }
             $top = $top + $TextHeight + 50;
         }
     }
     /* create the physical watermarked image to its destination */
     imagejpeg($image, $dest, 100);
     imagedestroy($image);
     //clean up some memory
     $resized = image_make_intermediate_size($source_dir . $watermark_image_name, $desired_width, $desired_height);
     //Use the WP function to resize the watermarked image to that specified in the settings
     if ($resized === false) {
         $wp_photo_gallery->debug_logger->log_debug('WPPGPhotoGallery::createWatermarkImage - image_make_intermediate_size failed and returned false!', 4);
     } else {
         rename($source_dir . $resized['file'], $source_dir . $watermark_image_name);
         //Since the above WP function uses a different naming convention we will change the name back to our convention
     }
 }
 /**
  * This method looks for images that don't have copies of the sizes defined by this plugin, and
  * then tries to make those copies. It returns an array of messages divided into error messages and
  * success messages. It only makes copies for X images at a time based on form selection.
  *
  * Also the same routine (for now) for deleting images and cleaning the attachment metadata
  *
  * @since       0.1
  * @uses        global $_wp_additional_image_sizes WP since 0.1.5
  * @uses        ZUI_WpAdditionalImageSizes::getAllImageAttachments()
  * @uses        ZUI_WpAdditionalImageSizes::getSizesWp()
  * @uses        ZUI_WpAdditionalImageSizes::getSizesCustom()  since 0.1.3
  * @uses        ZUI_WpAdditionalImageSizes::getAllImageSizes() since 0.1.3
  * @uses        ZUI_WpAdditionalImageSizes::mightBreakScriptToAvoidTimeout()
  * @uses        wp_upload_dir() WP function
  * @uses        wp_get_attachment_metadata() WP function
  * @uses        wp_update_attachment_metadata() WP function
  * @uses        get_post_meta() WP function
  * @uses        image_make_intermediate_size() WP function
  * @uses        get_option() WP function
  * @return      array
  * @todo        abstract create/delete better
  * @todo        minimize the number of variables, especially the flags
  */
 function regenerateImages()
 {
     global $_wp_additional_image_sizes;
     // Need this to prevent deleting legit set_post_thumbnail_size() and add_image_size() images
     // Set it up
     $start = strtotime('now');
     $max_execution_time = ini_get('max_execution_time');
     $max_execution_time = round($max_execution_time / 1.25);
     // Let's divide that max_execution_time by 1.25 just to play it a little bit safe (we don't know when WordPress started to run so $now is off as well)
     $did_increase_time_limit = FALSE;
     // Flag to be able to let them know we had to increase the time limit and still tell them we succeeded - clumsy as hell
     $did_finish_batch = TRUE;
     // Flag to know if we finished the batch or aborted - set to FALSE if we break the processing loop
     $did_delete_an_image = FALSE;
     // Flag to know if we deleted (or would have) any images or attacment metadata
     $did_resize_an_image = FALSE;
     // Flag to know if we resized (or would have) any images to customize success message in conjunction with $did_finish_all
     $did_finish_all = FALSE;
     // Flag to know if we finished them ALL - set to TRUE if a query for images comes up empty
     $messages = array();
     // Sent back to managePost() and viewOptionsPage() to print results
     $i = 0;
     // How many images we managed to process before we stopped the script to prevent a timeout
     $offset = isset($_POST['offset']) && 0 < $_POST['offset'] ? $_POST['offset'] - 1 : 0;
     // Where we should start from; for get_post() in getAllImageAttachments()
     $numberposts = isset($_POST['numberposts']) && 0 < $_POST['numberposts'] ? $_POST['numberposts'] : 50;
     $basedir = wp_upload_dir();
     $basedir = $basedir['basedir'];
     $sizes_wp = self::getSizesWp();
     // Set the sizes we are going to do based on site/blog owner choice
     // For delete this defaults to all
     if (isset($_POST['sizes_to_check']) && 'all' != $_POST['sizes_to_check']) {
         switch ($_POST['sizes_to_check']) {
             case "custom_only":
                 $sizes_to_check = self::getSizesCustom();
                 $messages['success'][] = 'Checked custom image sizes only.';
                 break;
             case "wordpress_only":
                 $sizes_to_check = $sizes_wp;
                 $messages['success'][] = 'Checked WordPress sizes (thumbnail, medium, large) only.';
                 break;
             default:
                 $sizes_to_check = array_intersect_key(self::getSizesCustom(), array($_POST['sizes_to_check'] => array()));
                 // This is super sloppy but for now there can be only one
                 $messages['success'][] = "Checked <strong>{$_POST['sizes_to_check']}</strong> image size only.";
                 break;
         }
     } else {
         if (isset($_POST['sizes_to_check']) && 'all' == $_POST['sizes_to_check']) {
             $sizes_to_check = self::getAllImageSizes();
             $messages['success'][] = 'Checked all custom and WordPress (thumbnail, medium, large) image sizes.';
         } else {
             if (isset($_POST['delete_images_for_deleted_sizes'])) {
                 $sizes_to_check = self::getAllImageSizes();
                 $messages['success'][] = 'Checked all images metadata.';
             }
         }
     }
     // Get an image batch with the quantity they requested
     $images = self::getAllImageAttachments(array('offset' => $offset, 'numberposts' => $numberposts));
     // Get image attachements starting at the offset
     // Loop the batch and resize as necessary
     if (!empty($images)) {
         foreach ($images as $image) {
             $metadata = wp_get_attachment_metadata($image->ID);
             $file = get_post_meta($image->ID, '_wp_attached_file', true);
             if (isset($_POST['regenerate_images'])) {
                 // We can skip this if not regenerating - abstract and separate regenerate/delete
                 foreach ($sizes_to_check as $size => $values) {
                     // Check to see if we are close to timing out - GRRR redundancy - we have to check this in the image loop as well if this is a delete - we need to abstract and separate regenerate/delete
                     $do_break_script = self::mightBreakScriptToAvoidTimeout($start, $max_execution_time);
                     if (TRUE === $do_break_script) {
                         $did_finish_batch = FALSE;
                         $did_finish_all = FALSE;
                         break 2;
                     } else {
                         if ('extended' === $do_break_script) {
                             $messages['success'][] = 'We increased the time limit at your request.';
                             $did_increase_time_limit = TRUE;
                         }
                     }
                     $size_width = $sizes_to_check[$size]['size_w'];
                     $size_height = $sizes_to_check[$size]['size_h'];
                     $size_crop = $sizes_to_check[$size]['crop'];
                     // We will try to make the size if:
                     //      size does not exist in the image meta data yet
                     //      OR if the size DOES exist in the image meta data but has changed (new size has a width AND metadata width doesn't match new width AND metadata height doesn't match new height)
                     if (isset($_POST['regenerate_images']) && (!isset($metadata['sizes'][$size]) || !empty($sizes_to_check[$size]['size_w']) && ($metadata['sizes'][$size]['width'] != $sizes_to_check[$size]['size_w'] && $metadata['sizes'][$size]['height'] != $sizes_to_check[$size]['size_h']))) {
                         $image_path = $basedir . '/' . $file;
                         // Simulate resize or do it for real?
                         if (isset($_POST['simulate_resize'])) {
                             $result = self::simulate_image_make_intermediate_size($image_path, $size_width, $size_height, $size_crop);
                         } else {
                             $result = image_make_intermediate_size($image_path, $size_width, $size_height, $size_crop);
                         }
                         // If the image was (or would be) resized
                         if ($result) {
                             if (isset($_POST['simulate_resize'])) {
                                 // Just a simulation
                                 if (isset($_POST['replace_sizes']) && array_key_exists($size, $sizes_wp)) {
                                     $messages['success'][] = "WOULD REPLACE: {$metadata['sizes'][$size]['file']} for new {$size} size";
                                 }
                                 $messages['success'][] = '<strong>WOULD CREATE:</strong> "' . $image->post_title . '" to size "' . $size . '"';
                             } else {
                                 // WP sizes cannot be deleted later so clean up as we go is in order
                                 // If they want us to and this size is a WP size
                                 if (isset($_POST['replace_sizes']) && array_key_exists($size, $sizes_wp)) {
                                     $path_parts = pathinfo($basedir . '/' . $file);
                                     $delete_wp_file = $path_parts['dirname'] . "/" . $metadata['sizes'][$size]['file'];
                                     //$delete_wp_file = $basedir . '/' . $metadata['sizes'][$size]['file'];
                                     $delete_wp_file = str_replace("\\", "/", $delete_wp_file);
                                     // Attempt to delete this old WP size
                                     if (@unlink($delete_wp_file)) {
                                         $messages['success'][] = "REPLACED: {$metadata['sizes'][$size]['file']} for new {$size} size";
                                     }
                                     // No alternate message on fail for now
                                 }
                                 // Update the metadata - if a wp replaced size named key is overwritten anyway
                                 $metadata['sizes'][$size] = array('file' => $result['file'], 'width' => $result['width'], 'height' => $result['height']);
                                 wp_update_attachment_metadata($image->ID, $metadata);
                                 $messages['success'][] = '<strong>CREATED:</strong> "' . $image->post_title . '" to size "' . $size . '"';
                             }
                             $did_resize_an_image = TRUE;
                         } else {
                             // Sick of looking at the skipped messages
                             if (isset($_POST['show_skipped'])) {
                                 // Assumed the image was too small to be created/resized so just send a tentative success message
                                 $messages['success'][] = 'SKIPPED: "' . $image->post_title . '" is already smaller than the requested size "' . $size . '"';
                             }
                         }
                     } else {
                         // Sick of looking at the skipped messages and we all know the predefined sizes exist anyway
                         if (isset($_POST['show_skipped']) && isset($_POST['simulate_resize'])) {
                             $messages['success'][] = 'WOULD SKIP: "' . $size . '" already exists for "' . $image->post_title . '"';
                         } else {
                             if (isset($_POST['show_skipped'])) {
                                 $messages['success'][] = 'SKIPPED: "' . $size . '" already exists for "' . $image->post_title . '"';
                             }
                         }
                     }
                     // End if we resized or not
                 }
                 // End sizes loop
             }
             if (!empty($_wp_additional_image_sizes)) {
                 $sizes_to_check_plus_additional = array_merge(array_keys($sizes_to_check), array_keys($_wp_additional_image_sizes));
             } else {
                 $sizes_to_check_plus_additional = array_keys($sizes_to_check);
             }
             $metadata_sizes_not_in_current_all_sizes = array_diff(array_keys($metadata['sizes']), $sizes_to_check_plus_additional);
             //sizes_to_check
             if (isset($_POST['delete_images_for_deleted_sizes'])) {
                 $metadata_after = $metadata;
                 // Leaving in some of this testing stuff for a couple of versions
                 /*
                 echo "<br />metadata before<pre>";
                 print_r($metadata);
                 echo "</pre><br />";
                 */
                 if (0 < count($metadata_sizes_not_in_current_all_sizes)) {
                     foreach ($metadata_sizes_not_in_current_all_sizes as $defunct_size) {
                         if ('post-thumbnail' == $defunct_size) {
                             continue;
                         }
                         // kludge to protect known named size created by set_post_thumbnail_size()
                         $path_parts = pathinfo($basedir . '/' . $file);
                         $delete_current_file = $path_parts['dirname'] . "/" . $metadata_after['sizes'][$defunct_size]['file'];
                         $delete_current_file = str_replace("\\", "/", $delete_current_file);
                         if (isset($_POST['simulate_delete'])) {
                             $image = wp_load_image($delete_current_file);
                             if (is_resource($image)) {
                                 $messages['success'][] = "<strong>WOULD DELETE:</strong> {$defunct_size} {$delete_current_file}";
                                 imagedestroy($image);
                                 // Free up memory
                             } else {
                                 $messages['errors'][] = "<strong>Can't find:</strong> {$delete_current_file}<br /><em>The attachment metadata would be deleted</em>";
                                 $messages['success'][] = "WOULD DELETE METADATA: for {$delete_current_file}";
                             }
                         } else {
                             if (@unlink($delete_current_file)) {
                                 $messages['success'][] = "<strong>DELETED:</strong> {$defunct_size} {$delete_current_file}";
                                 unset($metadata_after['sizes'][$defunct_size]);
                                 // We unset this in a copy of the metadata array to be sure (and for testing)
                             } else {
                                 $messages['success'][] = "Deleted metadata only:  {$defunct_size} {$delete_current_file}";
                                 unset($metadata_after['sizes'][$defunct_size]);
                                 // We unset this in a copy of the metadata array to be sure (and for testing)
                             }
                         }
                         $did_delete_an_image = TRUE;
                         // Check to see if we are close to timing out - GRRR redundancy - we have to check this in the size loop as well
                         $do_break_script = self::mightBreakScriptToAvoidTimeout($start, $max_execution_time);
                         if (TRUE === $do_break_script) {
                             $did_finish_batch = FALSE;
                             $did_finish_all = FALSE;
                             break 2;
                         } else {
                             if ('extended' === $do_break_script) {
                                 $messages['success'][] = 'We increased the time limit at your request.';
                                 $did_increase_time_limit = TRUE;
                             }
                         }
                     }
                 } else {
                     $messages['success'][] = "No sizes to delete for {$image->post_title}";
                 }
                 // UPDATE THE METADATA with the removed/deleted sizes
                 if (!isset($_POST['simulate_delete'])) {
                     wp_update_attachment_metadata($image->ID, $metadata_after);
                 }
                 /* // Leaving in some of this testing stuff for a couple of versions
                    echo "<br />metadata after<pre>";
                    print_r($metadata_after);
                    echo "</pre><br />";
                    */
             }
             $i++;
             $offset++;
         }
         // End images loop
     } else {
         $did_finish_all = TRUE;
     }
     // End if we have images
     // Since we finished the batch we should did a quick check for one more
     if ($did_finish_batch) {
         $images = self::getAllImageAttachments(array('offset' => $offset, 'numberposts' => 1));
         // we might have finished with this batch
         if (empty($images)) {
             $did_finish_all = TRUE;
         }
         // Yay we are done!
     }
     // Set the number of images we got to this attempt
     self::$_images_regenerated_this_attempt = $i;
     // Set the continue form "submit/click" link
     if (isset($_POST['delete_images_for_deleted_sizes'])) {
         $continue_link = "<a id='continue_deleting'>Continue deleting where we left off with the same settings</a>";
     } else {
         $continue_link = "<a id='continue_creating'>Continue creating where we left off with the same settings</a>";
     }
     // Give them a final status message for this batch
     if (!$did_resize_an_image && $did_finish_all && !isset($_POST['delete_images_for_deleted_sizes'])) {
         $messages['success'][] = 'All is well, no new copies created.';
         $i = 0;
         // Reset because we are done!
     } else {
         if (!$did_delete_an_image && $did_finish_all && isset($_POST['delete_images_for_deleted_sizes'])) {
             $messages['success'][] = 'All is well, no images to delete.';
             $i = 0;
             // Reset because we are done!
         } else {
             if ($did_finish_all) {
                 $messages['success'][] = '<strong>All done!</strong>';
                 $i = 0;
                 // Reset because we finished!
             } else {
                 if ($did_finish_batch) {
                     // We finished the request batch quantity but not all of the images
                     $messages['success'][] = "We finished checking a whole batch of {$i}.<br />Consider increasing the number of images per batch until you start seeing the friendly 'we had to stop the script message'.";
                     $messages['success'][] = "<strong>But...we're not quite finished yet. {$continue_link} or use the form to adjust settings and continue.</strong>";
                     self::$_images_regenerate_from_offset = $offset;
                 } else {
                     // We aborted the script to avoid timing out
                     $messages['success'][] = "We checked {$i} images out of an attempted {$numberposts}.";
                     $messages['success'][] = "<strong>Not quite finished yet. {$continue_link} or use the form to adjust settings and continue.</strong>";
                     self::$_images_regenerate_from_offset = $offset;
                 }
             }
         }
     }
     return $messages;
 }