コード例 #1
1
ファイル: AB_CompanyForm.php プロジェクト: patrickcurl/monks
 /**
  * @param array $post
  * @param array $files
  */
 public function bind(array $post, array $files = array())
 {
     parent::bind($post, $files);
     // Remove the old image.
     if (isset($post['ab_remove_logo']) && file_exists(get_option('ab_settings_company_logo_path'))) {
         unlink(get_option('ab_settings_company_logo_path'));
         update_option('ab_settings_company_logo_path', '');
         update_option('ab_settings_company_logo_url', '');
     }
     // And add new.
     if (isset($files['ab_settings_company_logo']) && $files['ab_settings_company_logo']['tmp_name']) {
         if (in_array($files['ab_settings_company_logo']['type'], array("image/gif", "image/jpeg", "image/png"))) {
             $uploaded = wp_handle_upload($files['ab_settings_company_logo'], array('test_form' => false));
             if ($uploaded) {
                 $editor = wp_get_image_editor($uploaded['file']);
                 $editor->resize(200, 200);
                 $editor->save($uploaded['file']);
                 $this->data['ab_settings_company_logo_path'] = $uploaded['file'];
                 $this->data['ab_settings_company_logo_url'] = $uploaded['url'];
                 // Remove old image.
                 if (file_exists(get_option('ab_settings_company_logo_path'))) {
                     unlink(get_option('ab_settings_company_logo_path'));
                 }
             }
         }
     }
 }
コード例 #2
0
ファイル: Letterbox.php プロジェクト: rpkoller/timber
 /**
  * Performs the actual image manipulation,
  * including saving the target file.
  *
  * @param  string $load_filename filepath (not URL) to source file
  *                               (ex: /src/var/www/wp-content/uploads/my-pic.jpg)
  * @param  string $save_filename filepath (not URL) where result file should be saved
  *                               (ex: /src/var/www/wp-content/uploads/my-pic-lbox-300x200-FF3366.jpg)
  * @return bool                  true if everything went fine, false otherwise
  */
 public function run($load_filename, $save_filename)
 {
     $w = $this->w;
     $h = $this->h;
     $bg = imagecreatetruecolor($w, $h);
     $c = self::hexrgb($this->color);
     $bgColor = imagecolorallocate($bg, $c['red'], $c['green'], $c['blue']);
     imagefill($bg, 0, 0, $bgColor);
     $image = wp_get_image_editor($load_filename);
     if (!is_wp_error($image)) {
         $current_size = $image->get_size();
         $quality = $image->get_quality();
         $ow = $current_size['width'];
         $oh = $current_size['height'];
         $new_aspect = $w / $h;
         $old_aspect = $ow / $oh;
         if ($new_aspect > $old_aspect) {
             //taller than goal
             $h_scale = $h / $oh;
             $owt = $ow * $h_scale;
             $y = 0;
             $x = $w / 2 - $owt / 2;
             $oht = $h;
             $image->crop(0, 0, $ow, $oh, $owt, $oht);
         } else {
             $w_scale = $w / $ow;
             $oht = $oh * $w_scale;
             $x = 0;
             $y = $h / 2 - $oht / 2;
             $owt = $w;
             $image->crop(0, 0, $ow, $oh, $owt, $oht);
         }
         $result = $image->save($save_filename);
         $func = 'imagecreatefromjpeg';
         $save_func = 'imagejpeg';
         $ext = pathinfo($save_filename, PATHINFO_EXTENSION);
         if ($ext == 'gif') {
             $func = 'imagecreatefromgif';
             $save_func = 'imagegif';
         } else {
             if ($ext == 'png') {
                 $func = 'imagecreatefrompng';
                 $save_func = 'imagepng';
                 if ($quality > 9) {
                     $quality = $quality / 10;
                     $quality = round(10 - $quality);
                 }
             }
         }
         $image = $func($save_filename);
         imagecopy($bg, $image, $x, $y, 0, 0, $owt, $oht);
         if ($save_func === 'imagegif') {
             return $save_func($bg, $save_filename);
         }
         return $save_func($bg, $save_filename, $quality);
     } else {
         Helper::error_log($image);
     }
     return false;
 }
コード例 #3
0
ファイル: wr2x_vt_resize.php プロジェクト: roycocup/enclothed
 function wr2x_vt_resize($file_path, $width, $height, $newfile)
 {
     $orig_size = getimagesize($file_path);
     $image_src[0] = $file_path;
     $image_src[1] = $orig_size[0];
     $image_src[2] = $orig_size[1];
     $file_info = pathinfo($file_path);
     $extension = '.' . $file_info['extension'];
     $no_ext_path = $file_info['dirname'] . '/' . $file_info['filename'];
     $cropped_img_path = $no_ext_path . '-' . $width . 'x' . $height . "-tmp" . $extension;
     $image = wp_get_image_editor($file_path);
     $image->resize($width, $height, true);
     $quality = wr2x_getoption("image_quality", "wr2x_advanced", "80");
     if (is_numeric($quality)) {
         $image->set_quality(intval($quality));
     }
     $image->save($cropped_img_path);
     if (rename($cropped_img_path, $newfile)) {
         $cropped_img_path = $newfile;
     }
     $new_img_size = getimagesize($cropped_img_path);
     $new_img = str_replace(basename($image_src[0]), basename($cropped_img_path), $image_src[0]);
     $vt_image = array('url' => $new_img, 'width' => $new_img_size[0], 'height' => $new_img_size[1]);
     return $vt_image;
 }
コード例 #4
0
function cropImageWithFaceDectection($metadata, $attachment_id)
{
    if (!isset($metadata['sizes'])) {
        return $metadata;
    }
    $upload_path = wp_upload_dir();
    $path = $upload_path['basedir'];
    //handle the different media upload directory structures
    if (isset($path)) {
        $file = trailingslashit($upload_path['basedir'] . '/') . $metadata['file'];
    } else {
        $file = trailingslashit($upload_path['path']) . $metadata['file'];
    }
    $client = new Client('5e3a3ac24363af113e04a58c61637ea4', 'sXA4iYYphLzg1z8IAcFAtPf8UdcXKwHm', 'http://apicn.faceplusplus.com');
    /** @var \FaceCrop\Type\Face[] $result */
    $result = $client->detect('http://showbizviet.vn/upload/files/data/2013/8/2/18/466473/1825600192_cham-soc-da-chuan-nhu-ngoc-trinh%202.jpg');
    $height = $result[0]->getPosition()->getHeight();
    $width = $result[0]->getPosition()->getWidth();
    $leftEye = $result[0]->getPosition()->getEyeLeft();
    $mouthRight = $result[0]->getPosition()->getMouthRight();
    $editor = wp_get_image_editor($file);
    $startX = $leftEye->x / $width * 100;
    $startY = $leftEye->y / $height * 100;
    $editor->crop($startX - 100, $startY - 100, 500, 300, 500, 300, false);
    $result = $editor->save($file);
    wp_send_json(array($result, $file));
    return $metadata;
}
コード例 #5
0
ファイル: functions.php プロジェクト: TakenCdosG/chefs
function get_image_url($path, $id, $width, $height)
{
    $image_path = $path;
    $upload_directory = wp_upload_dir();
    $modified_image_directory = $upload_directory["basedir"] . "/blog/" . $id . "/";
    if (!file_exists($modified_image_directory)) {
        wp_mkdir_p($modified_image_directory);
    }
    $file_name_with_ending = explode("/", $image_path);
    $file_name_with_ending = $file_name_with_ending[count($file_name_with_ending) - 1];
    $file_name_without_ending = explode(".", $file_name_with_ending);
    $file_ending = $file_name_without_ending[count($file_name_without_ending) - 1];
    $file_name_without_ending = $file_name_without_ending[count($file_name_without_ending) - 2];
    $modified_image_path = $modified_image_directory . md5($file_name_without_ending) . "." . $file_ending;
    if (!file_exists($modified_image_path)) {
        $image = wp_get_image_editor($image_path);
        if (!is_wp_error($image)) {
            $rotate = 180;
            $modified_file_name_without_ending = $file_name_without_ending . "-" . $width . "x" . $height . "-" . $rotate . "dg";
            $image->resize($width, $height);
            $image->rotate($rotate);
            $image->save($modified_file_name_without_ending);
        }
    }
    $modified_image_url = $upload_directory["url"] . "/" . $modified_file_name_without_ending . "." . $file_ending;
    return $modified_image_url;
}
コード例 #6
0
 public function wp_generate_attachment_metadata($metadata, $attachment_id)
 {
     $attachment = get_attached_file($attachment_id);
     if (!preg_match('!^image/!', get_post_mime_type($attachment_id)) || !file_is_displayable_image($attachment)) {
         return $metadata;
     }
     $image_sizes = Helper::get_image_sizes();
     foreach ($image_sizes as $size_name => $size_attributes) {
         if (!empty($metadata['sizes'][$size_name])) {
             continue;
         }
         $image = wp_get_image_editor($attachment);
         if (is_wp_error($image)) {
             continue;
         }
         $resized = $image->resize($size_attributes['width'], $size_attributes['height'], $size_attributes['crop']);
         $image_size = $image->get_size();
         if (!is_wp_error($resized) && !empty($image_size)) {
             $filename = wp_basename($image->generate_filename());
             $extension = pathinfo($filename, PATHINFO_EXTENSION);
             $mime_type = $this->get_mime_type($extension);
             $metadata['sizes'][$size_name] = array('file' => $filename, 'width' => $image_size['width'], 'height' => $image_size['height'], 'mime-type' => $mime_type);
         }
     }
     return $metadata;
 }
コード例 #7
0
ファイル: admin.php プロジェクト: abacusadvertising/groundup
 function groundup_image_suffix($image)
 {
     // Split the $image path into directory/extension/name
     $info = pathinfo($image);
     $dir = $info['dirname'] . '/';
     $ext = '.' . $info['extension'];
     $file_name = wp_basename($image, "{$ext}");
     $image_name = substr($file_name, 0, strrpos($file_name, '-'));
     // Get image information
     $img = wp_get_image_editor($image);
     // Get image size, width and height
     $img_size = $img->get_size();
     // Get new image suffix by comparing image sizes
     $image_sizes = get_intermediate_image_sizes();
     foreach ($image_sizes as $size) {
         $rename = false;
         $sizeInfo = get_image_size_data($size);
         if ($img_size['width'] == $sizeInfo['width'] && $img_size['height'] <= $sizeInfo['height']) {
             $rename = true;
         } elseif ($img_size['height'] == $sizeInfo['height'] && $img_size['width'] <= $sizeInfo['width']) {
             $rename = true;
         }
         if ($rename == true) {
             // Rename image
             $new_name = $dir . $image_name . '-' . $size . $ext;
             // Rename the intermediate size
             $rename_success = rename($image, $new_name);
             if ($rename_success) {
                 return $new_name;
             }
         }
     }
     // do nothing if not renamed
     return $image;
 }
コード例 #8
0
 public function __construct($file)
 {
     $this->setup();
     $this->file = $this->sanitize_file_path($file);
     $this->editor = wp_get_image_editor($this->source_file());
     return $this;
 }
コード例 #9
0
 public function getAttachment($attachmentId, $width = null, $height = null, $crop = false, $bookId = false)
 {
     $width = (int) $width;
     $height = (int) $height;
     $cachedUrl = $this->getAttachUrlCached($attachmentId, $width, $height, $crop, $bookId);
     if ($cachedUrl) {
         return $cachedUrl;
     }
     $attachment = wp_prepare_attachment_for_js($attachmentId);
     $filePath = $this->getFilePath($attachment['url']);
     // First try:
     // Trying to find image in wordpress sizes.
     if (!empty($attachment) && $attachment['sizes']) {
         foreach ($attachment['sizes'] as $size) {
             if ($width && $width === $size['width'] && ($height && $height === $size['height'])) {
                 $this->saveAttachUrlCached($attachmentId, $width, $height, $crop, $bookId, $size['url']);
                 return $size['url'];
             }
         }
     }
     // Second try
     // Trying to find cropped images.
     $filename = pathinfo($filePath, PATHINFO_FILENAME);
     $filename = $filename . '-' . $width . 'x' . $height . '.' . pathinfo($filePath, PATHINFO_EXTENSION);
     if (is_file($file = dirname($filePath) . '/' . $filename)) {
         $imgUrl = str_replace(ABSPATH, get_bloginfo('wpurl') . '/', $file);
         $this->saveAttachUrlCached($attachmentId, $width, $height, $crop, $bookId, $imgUrl);
         return str_replace(ABSPATH, get_bloginfo('wpurl') . '/', $file);
     }
     // Third and last try
     $editor = wp_get_image_editor($filePath);
     if (!has_filter('image_resize_dimensions', 'image_crop_dimensions')) {
         function image_crop_dimensions($default, $orig_w, $orig_h, $new_w, $new_h, $crop)
         {
             if (!$crop || !$new_w || !$new_h) {
                 return null;
             }
             $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
             $crop_w = round($new_w / $size_ratio);
             $crop_h = round($new_h / $size_ratio);
             $s_x = floor(($orig_w - $crop_w) / 2);
             $s_y = floor(($orig_h - $crop_h) / 2);
             return array(0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h);
         }
         add_filter('image_resize_dimensions', 'image_crop_dimensions', 10, 6);
     }
     if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, (bool) $crop))) {
         $imgUrl = isset($attachment['sizes'], $attachment['sizes']['full'], $attachment['sizes']['full']['url']) ? $attachment['sizes']['full']['url'] : $attachment['url'];
         $this->saveAttachUrlCached($attachmentId, $width, $height, $crop, $bookId, $imgUrl);
         return $imgUrl;
     }
     if (is_wp_error($data = $editor->save())) {
         return $attachment['sizes']['full']['url'];
     }
     $editor = null;
     unset($editor);
     $imgUrl = str_replace(ABSPATH, get_bloginfo('wpurl') . '/', $data['path']);
     $this->saveAttachUrlCached($attachmentId, $width, $height, $crop, $bookId, $imgUrl);
     return str_replace(ABSPATH, get_bloginfo('wpurl') . '/', $data['path']);
 }
コード例 #10
0
 /**
  * Performs the actual image manipulation,
  * including saving the target file.
  *
  * @param  string $load_filename filepath (not URL) to source file
  *                               (ex: /src/var/www/wp-content/uploads/my-pic.jpg)
  * @param  string $save_filename filepath (not URL) where result file should be saved
  *                               (ex: /src/var/www/wp-content/uploads/my-pic@2x.jpg)
  * @return bool                  true if everything went fine, false otherwise
  */
 function run($load_filename, $save_filename)
 {
     $image = wp_get_image_editor($load_filename);
     if (!is_wp_error($image)) {
         $current_size = $image->get_size();
         $src_w = $current_size['width'];
         $src_h = $current_size['height'];
         // Get ratios
         $w = $src_w * $this->factor;
         $h = $src_h * $this->factor;
         $image->crop(0, 0, $src_w, $src_h, $w, $h);
         $result = $image->save($save_filename);
         if (is_wp_error($result)) {
             error_log('Error resizing image');
             error_log(print_r($result, true));
             return false;
         } else {
             return true;
         }
     } else {
         if (isset($image->error_data['error_loading_image'])) {
             TimberHelper::error_log('Error loading ' . $image->error_data['error_loading_image']);
         } else {
             TimberHelper::error_log($image);
         }
     }
     return false;
 }
function hack_image_make_intermediate_size($file, $width, $height, $crop = false, $size = "")
{
    if ($width || $height) {
        if ($size == "thumbnail" || $size == "medium" || $size == "large") {
            $suffix = $size;
        } else {
            global $_wp_additional_image_sizes;
            if (isset($_wp_additional_image_sizes[$size])) {
                $suffix = $size;
            } else {
                $suffix = null;
            }
        }
        //コアファイルを触らずにサムネイル(jpg)のクオリティ値を変えられます。デフォルトは90。
        $image = wp_get_image_editor($file);
        // Return an implementation that extends <tt>WP_Image_Editor</tt>
        if (!is_wp_error($image)) {
            if (empty($suffix)) {
                $suffix = "{$width}x{$height}";
            }
            $pathinfo = pathinfo($file);
            $dir = $pathinfo['dirname'];
            $ext = $pathinfo['extension'];
            $name = basename($file, ".{$ext}");
            $resized_file = "{$dir}/{$name}-{$suffix}.{$ext}";
            $image->resize($width, $height, $crop);
            $image->save($resized_file);
            if ($info = getimagesize($resized_file)) {
                $resized_file = apply_filters('image_make_intermediate_size', $resized_file);
                return array('file' => wp_basename($resized_file), 'width' => $info[0], 'height' => $info[1], 'size' => $size);
            }
        }
    }
    return false;
}
コード例 #12
0
ファイル: Retina.php プロジェクト: darbymanning/Family-Church
 /**
  * Performs the actual image manipulation,
  * including saving the target file.
  *
  * @param  string $load_filename filepath (not URL) to source file
  *                               (ex: /src/var/www/wp-content/uploads/my-pic.jpg)
  * @param  string $save_filename filepath (not URL) where result file should be saved
  *                               (ex: /src/var/www/wp-content/uploads/my-pic@2x.jpg)
  * @return bool                  true if everything went fine, false otherwise
  */
 public function run($load_filename, $save_filename)
 {
     $image = wp_get_image_editor($load_filename);
     if (!is_wp_error($image)) {
         $current_size = $image->get_size();
         $src_w = $current_size['width'];
         $src_h = $current_size['height'];
         // Get ratios
         $w = $src_w * $this->factor;
         $h = $src_h * $this->factor;
         $image->crop(0, 0, $src_w, $src_h, $w, $h);
         $result = $image->save($save_filename);
         if (is_wp_error($result)) {
             // @codeCoverageIgnoreStart
             Helper::error_log('Error resizing image');
             Helper::error_log($result);
             return false;
             // @codeCoverageIgnoreEnd
         }
         return true;
     } else {
         if (isset($image->error_data['error_loading_image'])) {
             Helper::error_log('Error loading ' . $image->error_data['error_loading_image']);
             return false;
         }
     }
     Helper::error_log($image);
     return false;
 }
コード例 #13
0
 /**
  * 
  * init image parameters from url
  */
 private function initImageParams($urlImage, $size = UniteFunctionsWPBiz::THUMB_MEDIUM, $ratio = 'none', $refresh = 'false')
 {
     if (is_numeric($urlImage)) {
         $this->thumbID = $urlImage;
         $this->imageUrl = UniteFunctionsWPBiz::getUrlAttachmentImage($this->thumbID, $size);
         $this->imageUrlOrig = UniteFunctionsWPBiz::getUrlAttachmentImage($this->thumbID, 'full');
     } else {
         $this->imageUrl = $urlImage;
         $this->imageUrlOrig = $urlImage;
     }
     //set image path, file and url
     if (!empty($this->imageUrl)) {
         $this->imageFilepath = UniteFunctionsWPBiz::getImagePathFromURL($this->imageUrl);
         $realPath = UniteFunctionsWPBiz::getPathUploads() . $this->imageFilepath;
         //scale img if needed
         if ($ratio !== 'none') {
             $ratio = explode('_', $ratio);
             if (count($ratio) == 2) {
                 $image = wp_get_image_editor($realPath);
                 if (!is_wp_error($image)) {
                     $origSize = $image->get_size();
                     if (isset($origSize['width']) && $origSize['width'] > 0 && isset($origSize['height']) && $origSize['height'] > 0) {
                         $doCreate = true;
                         //get new dimensions based on the scale ratio
                         $newSize = UniteFunctionsBiz::getImageSizeByRatio($origSize['width'], $origSize['height'], $ratio['0'], $ratio['1']);
                         //check if file exists with dimensions
                         $suffix = $image->get_suffix();
                         $fnCheck = $image->generate_filename();
                         $fnCheck = str_replace($suffix . '.', $newSize['0'] . 'x' . $newSize['1'] . '.', $fnCheck);
                         //check if file exists
                         if (file_exists($fnCheck) != false) {
                             if ($refresh == 'false') {
                                 $doCreate = false;
                             }
                         }
                         //refresh
                         if ($doCreate) {
                             $image->resize($newSize['0'], $newSize['1'], true);
                             $newImage = $image->generate_filename();
                             $image->save($newImage);
                         } else {
                             $newImage = $fnCheck;
                         }
                         if (trim($newImage) !== '') {
                             $this->imageUrl = str_replace(ABSPATH, '', $newImage);
                             $this->imageFilepath = UniteFunctionsWPBiz::getImagePathFromURL($this->imageUrl);
                             $realPath = UniteFunctionsWPBiz::getPathUploads() . $this->imageFilepath;
                             $this->imageUrl = get_bloginfo('wpurl') . '/' . $this->imageUrl;
                         }
                     }
                 }
             }
         }
         if (file_exists($realPath) == false || is_file($realPath) == false) {
             $this->imageFilepath = "";
         }
         $this->imageFilename = basename($this->imageUrl);
     }
 }
コード例 #14
0
ファイル: MF_thumb.php プロジェクト: robre/Magic-Fields-2
 /**
  * This function is almost equal to the image_resize (native function of wordpress)
  */
 function image_resize35($file, $max_w, $max_h, $crop = false, $far = false, $iar = false, $dest_path = null, $jpeg_quality = 90)
 {
     $image = wp_get_image_editor($file);
     if (is_wp_error($image)) {
         return $image;
     }
     $size = @getimagesize($file);
     if (!$size) {
         return new WP_Error('invalid_image', __('Could not read image size'), $file);
     }
     list($orig_w, $orig_h, $orig_type) = $size;
     $dims = mf_image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop, $far, $iar);
     if (!$dims) {
         $dims = array(0, 0, 0, 0, $orig_w, $orig_h, $orig_w, $orig_h);
     }
     list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
     $newimage = imagecreatetruecolor($dst_w, $dst_h);
     imagealphablending($newimage, false);
     imagesavealpha($newimage, true);
     $transparent = imagecolorallocatealpha($newimage, 255, 255, 255, 127);
     imagefilledrectangle($newimage, 0, 0, $dst_w, $dst_h, $transparent);
     @ini_set('memory_limit', apply_filters('image_memory_limit', WP_MAX_MEMORY_LIMIT));
     $imageTmp = imagecreatefromstring(file_get_contents($file));
     imagecopyresampled($newimage, $imageTmp, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
     // convert from full colors to index colors, like original PNG.
     if (IMAGETYPE_PNG == $orig_type && !imageistruecolor($imageTmp)) {
         imagetruecolortopalette($newimage, false, imagecolorstotal($imageTmp));
     }
     // we don't need the original in memory anymore
     imagedestroy($imageTmp);
     $info = pathinfo($dest_path);
     $dir = $info['dirname'];
     $ext = $info['extension'];
     $name = basename($dest_path, ".{$ext}");
     $destfilename = "{$dir}/{$name}.{$ext}";
     if (IMAGETYPE_GIF == $orig_type) {
         if (!imagegif($newimage, $destfilename)) {
             return new WP_Error('resize_path_invalid', __('Resize path invalid'));
         }
     } elseif (IMAGETYPE_PNG == $orig_type) {
         if (!imagepng($newimage, $destfilename)) {
             return new WP_Error('resize_path_invalid', __('Resize path invalid'));
         }
     } else {
         // all other formats are converted to jpg
         //Todo: add option for use progresive JPG
         //imageinterlace($newimage, true); //Progressive JPG
         if (!imagejpeg($newimage, $destfilename, apply_filters('jpeg_quality', $jpeg_quality, 'image_resize'))) {
             return new WP_Error('resize_path_invalid', __('Resize path invalid'));
         }
     }
     imagedestroy($newimage);
     // Set correct file permissions
     $stat = stat(dirname($destfilename));
     $perms = $stat['mode'] & 0666;
     //same permissions as parent folder, strip off the executable bits
     @chmod($destfilename, $perms);
     return $destfilename;
 }
コード例 #15
0
 /**
  * Convert image to a new mime type.
  *
  * @since 1.0
  *
  * @param string The filepath of an image
  * @param string The new mime type of the image. By default jpg
  * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
  */
 public static function convert_image($filepath, $new_mime_type = null)
 {
     if (!$new_mime_type) {
         $new_mime_type = self::$new_type;
     }
     $editor = wp_get_image_editor($filepath);
     return $editor->save($filepath, $new_mime_type);
 }
コード例 #16
0
 public function process($attachment, $width, $height, $crop = false)
 {
     $attachment_info = $this->get_attachment_info($attachment);
     if (!$attachment_info) {
         return new WP_Error('invalid_attachment', 'Invalid Attachment', $attachment);
     }
     $file_path = $attachment_info['path'];
     $info = pathinfo($file_path);
     $dir = $info['dirname'];
     $ext = isset($info['extension']) ? $info['extension'] : 'jpg';
     $name = wp_basename($file_path, ".{$ext}");
     $name = preg_replace('/(.+)(\\-\\d+x\\d+)$/', '$1', $name);
     // Suffix applied to filename
     $suffix = "{$width}x{$height}";
     // Get the destination file name
     $destination_file_name = "{$dir}/{$name}-{$suffix}.{$ext}";
     // No need to resize & create a new image if it already exists
     if (!file_exists($destination_file_name)) {
         //Image Resize
         $editor = wp_get_image_editor($file_path);
         if (is_wp_error($editor)) {
             return new WP_Error('wp_image_editor', 'WP Image editor can\'t resize this attachment', $attachment);
         }
         // Get the original image size
         $size = $editor->get_size();
         $orig_width = $size['width'];
         $orig_height = $size['height'];
         $src_x = $src_y = 0;
         $src_w = $orig_width;
         $src_h = $orig_height;
         if ($crop) {
             $cmp_x = $orig_width / $width;
             $cmp_y = $orig_height / $height;
             // Calculate x or y coordinate, and width or height of source
             if ($cmp_x > $cmp_y) {
                 $src_w = round($orig_width / $cmp_x * $cmp_y);
                 $src_x = round(($orig_width - $orig_width / $cmp_x * $cmp_y) / 2);
             } else {
                 if ($cmp_y > $cmp_x) {
                     $src_h = round($orig_height / $cmp_y * $cmp_x);
                     $src_y = round(($orig_height - $orig_height / $cmp_y * $cmp_x) / 2);
                 }
             }
         }
         $editor->crop($src_x, $src_y, $src_w, $src_h, $width, $height);
         $saved = $editor->save($destination_file_name);
         $images = wp_get_attachment_metadata($attachment_info['id']);
         if (!empty($images['resizes']) && is_array($images['resizes'])) {
             foreach ($images['resizes'] as $image_size => $image_path) {
                 $images['resizes'][$image_size] = addslashes($image_path);
             }
         }
         $uploads_dir = wp_upload_dir();
         $images['resizes'][$suffix] = $uploads_dir['subdir'] . '/' . $saved['file'];
         wp_update_attachment_metadata($attachment_info['id'], $images);
     }
     return array('id' => $attachment_info['id'], 'src' => str_replace(basename($attachment_info['url']), basename($destination_file_name), $attachment_info['url']));
 }
コード例 #17
0
 protected function stream()
 {
     $image = wp_get_image_editor($this->new_image_path);
     status_header(200);
     $stream = $image->stream();
     if (is_wp_error($stream)) {
         status_header(500);
         die($stream->get_error_message());
     }
 }
コード例 #18
0
 /**
  * Image moving and resizing routine.
  *
  * Relies on WP built-in image resizing.
  *
  * @param array Image paths to move from temp directory
  * @return mixed Array of new image paths, or (bool)false on failure.
  * @access private
  */
 function move_images($imgs)
 {
     if (!$imgs) {
         return false;
     }
     if (!is_array($imgs)) {
         $imgs = array($imgs);
     }
     global $bp;
     $ret = array();
     $thumb_w = get_option('thumbnail_size_w');
     $thumb_w = $thumb_w ? $thumb_w : 100;
     $thumb_h = get_option('thumbnail_size_h');
     $thumb_h = $thumb_h ? $thumb_h : 100;
     // Override thumbnail image size in wp-config.php
     if (defined('BPFB_THUMBNAIL_IMAGE_SIZE')) {
         list($tw, $th) = explode('x', BPFB_THUMBNAIL_IMAGE_SIZE);
         $thumb_w = (int) $tw ? (int) $tw : $thumb_w;
         $thumb_h = (int) $th ? (int) $th : $thumb_h;
     }
     $processed = 0;
     foreach ($imgs as $img) {
         $processed++;
         if (BPFB_IMAGE_LIMIT && $processed > BPFB_IMAGE_LIMIT) {
             break;
         }
         // Do not even bother to process more.
         if (preg_match('!^https?:\\/\\/!i', $img)) {
             // Just add remote images
             $ret[] = $img;
             continue;
         }
         $pfx = $bp->loggedin_user->id . '_' . preg_replace('/ /', '', microtime());
         $tmp_img = realpath(BPFB_TEMP_IMAGE_DIR . $img);
         $new_img = BPFB_BASE_IMAGE_DIR . "{$pfx}_{$img}";
         if (@rename($tmp_img, $new_img)) {
             if (function_exists('wp_get_image_editor')) {
                 // New way of resizing the image
                 $image = wp_get_image_editor($new_img);
                 if (!is_wp_error($image)) {
                     $thumb_filename = $image->generate_filename('bpfbt');
                     $image->resize($thumb_w, $thumb_h, false);
                     $image->save($thumb_filename);
                 }
             } else {
                 // Old school fallback
                 image_resize($new_img, $thumb_w, $thumb_h, false, 'bpfbt');
             }
             $ret[] = pathinfo($new_img, PATHINFO_BASENAME);
         } else {
             return false;
         }
     }
     return $ret;
 }
コード例 #19
0
 public function image_downsize($out, $id, $size)
 {
     // we don't handle this
     if (is_array($size)) {
         return false;
     }
     $meta = wp_get_attachment_metadata($id);
     $wanted_width = $wanted_height = 0;
     if (empty($meta['file'])) {
         return false;
     }
     // get $size dimensions
     global $_wp_additional_image_sizes;
     if (isset($_wp_additional_image_sizes) && isset($_wp_additional_image_sizes[$size])) {
         $wanted_width = $_wp_additional_image_sizes[$size]['width'];
         $wanted_height = $_wp_additional_image_sizes[$size]['height'];
         $wanted_crop = isset($_wp_additional_image_sizes[$size]['crop']) ? $_wp_additional_image_sizes[$size]['crop'] : false;
     } else {
         if (in_array($size, array('thumbnail', 'medium', 'large'))) {
             $wanted_width = get_option($size . '_size_w');
             $wanted_height = get_option($size . '_size_h');
             $wanted_crop = 'thumbnail' === $size ? (bool) get_option('thumbnail_crop') : false;
         } else {
             // unknown size, bail out
             return false;
         }
     }
     if (0 === absint($wanted_width) && 0 === absint($wanted_height)) {
         return false;
     }
     if ($intermediate = image_get_intermediate_size($id, $size)) {
         return false;
     } else {
         // image size not found, create it
         $attachment_path = get_attached_file($id);
         $image_editor = wp_get_image_editor($attachment_path);
         if (!is_wp_error($image_editor)) {
             $image_editor->resize($wanted_width, $wanted_height, $wanted_crop);
             $result_image_size = $image_editor->get_size();
             $result_width = $result_image_size['width'];
             $result_height = $result_image_size['height'];
             $suffix = $result_width . 'x' . $result_height;
             $filename = $image_editor->generate_filename($suffix);
             $image_editor->save($filename);
             $meta['sizes'][$size] = array('file' => basename($filename), 'width' => $result_width, 'height' => $result_height, 'mime-type' => get_post_mime_type($id));
             wp_update_attachment_metadata($id, $meta);
         } else {
             return false;
         }
     }
     return false;
 }
コード例 #20
0
/**
 * Create retina-ready images
 *
 * Referenced via retina_support_attachment_meta().
 */
function retina_support_create_images($file, $width, $height, $crop = false)
{
    if ($width || $height) {
        $resized_file = wp_get_image_editor($file);
        if (!is_wp_error($resized_file)) {
            $filename = $resized_file->generate_filename($width . 'x' . $height . '@2x');
            $resized_file->resize($width * 2, $height * 2, $crop);
            $resized_file->save($filename);
            $info = $resized_file->get_size();
            return array('file' => wp_basename($filename), 'width' => $info['width'], 'height' => $info['height']);
        }
    }
    return false;
}
コード例 #21
0
ファイル: global.php プロジェクト: Akilan-i2i/imaginator
 function outdoor_make_retina_size($file, $width, $height, $crop = false)
 {
     if (!$file || !$width || !$height) {
         return false;
     }
     $resized_file = wp_get_image_editor($file);
     if (!is_wp_error($resized_file)) {
         $resized_file->resize($width * 2, $height * 2, $crop);
         $filename = $resized_file->generate_filename($width . 'x' . $height . '@2x');
         $resized_file->save($filename);
     }
     if (!is_wp_error($resized_file) && $resized_file && ($info = getimagesize($filename))) {
         return array('file' => wp_basename($filename), 'width' => $info[0], 'height' => $info[1]);
     }
 }
コード例 #22
0
 /**
  * Create @2x image.
  *
  * @param string $file
  * @param int $width
  * @param int $height
  * @param bool $crop
  * @return bool|array
  */
 public static function create_2x_image($file, $width, $height, $crop = false)
 {
     if (!$width && !$height) {
         return false;
     }
     $resized_file = wp_get_image_editor($file);
     if (is_wp_error($resized_file)) {
         return false;
     }
     $filename = $resized_file->generate_filename($width . 'x' . $height . '@2x');
     $resized_file->set_quality(80);
     $resized_file->resize($width * 2, $height * 2, $crop);
     $resized_file->save($filename);
     $info = $resized_file->get_size();
     return array('file' => wp_basename($filename), 'width' => $info['width'], 'height' => $info['height']);
 }
コード例 #23
0
ファイル: utils.php プロジェクト: jamesmallen/imsanity
/**
 * Replacement for deprecated image_resize function
 * @param string $file Image file path.
 * @param int $max_w Maximum width to resize to.
 * @param int $max_h Maximum height to resize to.
 * @param bool $crop Optional. Whether to crop image or resize.
 * @param string $suffix Optional. File suffix.
 * @param string $dest_path Optional. New image file path.
 * @param int $jpeg_quality Optional, default is 90. Image quality percentage.
 * @return mixed WP_Error on failure. String with new destination path.
 */
function imsanity_image_resize($file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90)
{
    if (function_exists('wp_get_image_editor')) {
        // WP 3.5 and up use the image editor
        $editor = wp_get_image_editor($file);
        if (is_wp_error($editor)) {
            return $editor;
        }
        $editor->set_quality($jpeg_quality);
        $ftype = pathinfo($file, PATHINFO_EXTENSION);
        // try to correct for auto-rotation if the info is available
        if (function_exists('exif_read_data') && ($ftype == 'jpg' || $ftype == 'jpeg')) {
            $exif = @exif_read_data($file);
            $orientation = is_array($exif) && array_key_exists('Orientation', $exif) ? $exif['Orientation'] : 0;
            switch ($orientation) {
                case 3:
                    $editor->rotate(180);
                    break;
                case 6:
                    $editor->rotate(-90);
                    break;
                case 8:
                    $editor->rotate(90);
                    break;
            }
        }
        $resized = $editor->resize($max_w, $max_h, $crop);
        if (is_wp_error($resized)) {
            return $resized;
        }
        $dest_file = $editor->generate_filename($suffix, $dest_path);
        // FIX: make sure that the destination file does not exist.  this fixes
        // an issue during bulk resize where one of the optimized media filenames may get
        // used as the temporary file, which causes it to be deleted.
        while (file_exists($dest_file)) {
            $dest_file = $editor->generate_filename('TMP', $dest_path);
        }
        $saved = $editor->save($dest_file);
        if (is_wp_error($saved)) {
            return $saved;
        }
        return $dest_file;
    } else {
        // wordpress prior to 3.5 uses the old image_resize function
        return image_resize($file, $max_w, $max_h, $crop, $suffix, $dest_path, $jpeg_quality);
    }
}
コード例 #24
0
ファイル: Image.php プロジェクト: hametuha/wpametu
 /**
  * Clone of image resize
  *
  * @see image_resize
  * @param string $file Image file path.
  * @param int $max_w Maximum width to resize to.
  * @param int $max_h Maximum height to resize to.
  * @param bool $crop Optional. Whether to crop image or resize.
  * @param string $suffix Optional. File suffix.
  * @param string $dest_path Optional. New image file path.
  * @param int $jpeg_quality Optional, default is 90. Image quality percentage.
  * @return mixed WP_Error on failure. String with new destination path.
  */
 public function trim($file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90)
 {
     $editor = wp_get_image_editor($file);
     if (is_wp_error($editor)) {
         return $editor;
     }
     $editor->set_quality($jpeg_quality);
     $resized = $editor->resize($max_w, $max_h, $crop);
     if (is_wp_error($resized)) {
         return $resized;
     }
     $dest_file = $editor->generate_filename($suffix, $dest_path);
     $saved = $editor->save($dest_file);
     if (is_wp_error($saved)) {
         return $saved;
     }
     return $dest_file;
 }
コード例 #25
0
ファイル: functions.php プロジェクト: jackey/xy
function get_attachment_image_thumbnail($postID, $fieldName, $size = array())
{
    $poster = get_post_meta($postID, $fieldName, true);
    if (!$poster) {
        return get_bloginfo('template_url') . '/images/blog-list_1.jpg';
    }
    $image = wp_get_attachment_metadata($poster);
    $srcImage = $image['file'];
    $uploadDir = wp_upload_dir();
    $editor = wp_get_image_editor($uploadDir['basedir'] . '/' . $srcImage);
    $editor->resize(270, 135, true);
    $baseName = pathinfo($srcImage, PATHINFO_DIRNAME);
    $fileName = pathinfo($srcImage, PATHINFO_FILENAME);
    $extName = pathinfo($srcImage, PATHINFO_EXTENSION);
    $distImage = $editor->save($uploadDir['basedir'] . "/{$baseName}/270x135-{$fileName}.{$extName}");
    $baseUrl = str_replace($uploadDir['basedir'], "", $distImage['path']);
    return $uploadDir['baseurl'] . '/' . $baseUrl;
}
コード例 #26
0
 function testResizeTallImage()
 {
     $data = array();
     $data['size'] = array('width' => 600);
     $upload_dir = wp_upload_dir();
     $this->copyTestImage('tall.jpg');
     $url = $upload_dir['url'] . '/tall.jpg';
     $data['test_image'] = $url;
     Timber::render('assets/image-test-one-param.twig', $data);
     $resized_path = $upload_dir['path'] . '/tall-r-' . $data['size']['width'] . 'x0.jpg';
     $exists = file_exists($resized_path);
     $this->assertTrue($exists);
     //make sure it's the width it's supposed to be
     $image = wp_get_image_editor($resized_path);
     $current_size = $image->get_size();
     $w = $current_size['width'];
     $this->assertEquals($w, 600);
 }
コード例 #27
0
function opanda_avatar()
{
    $leadId = isset($_GET['opanda_lead_id']) ? intval($_GET['opanda_lead_id']) : 0;
    if (empty($leadId)) {
        exit;
    }
    $size = isset($_GET['opanda_size']) ? intval($_GET['opanda_size']) : 40;
    if ($size > 500) {
        $size = 500;
    }
    if ($size <= 0) {
        $size = 40;
    }
    require_once OPANDA_BIZPANDA_DIR . '/admin/includes/leads.php';
    $imageSource = OPanda_Leads::getLeadField($leadId, 'externalImage');
    if (empty($imageSource) || !function_exists('wp_get_image_editor')) {
        exit;
    }
    $upload_dir = wp_upload_dir();
    $basePath = $upload_dir['path'] . '/bizpanda/avatars/';
    if (!file_exists($basePath) && !is_dir($basePath)) {
        mkdir($basePath, 0777, true);
    }
    $pathAvatar = $basePath . $leadId . 'x' . $size . '.jpeg';
    $pathOriginal = $basePath . $leadId . 'x' . $size . '_org.jpeg';
    $response = wp_remote_get($imageSource);
    if (is_wp_error($response) || !isset($response['headers']['content-type']) || !isset($response['body']) || empty($response['body']) || !preg_match("/image/i", $response['headers']['content-type'])) {
        OPanda_Leads::removeLeadField($leadId, 'externalImage');
        exit;
    }
    file_put_contents($pathOriginal, $response['body']);
    $image = wp_get_image_editor($pathOriginal);
    if (is_wp_error($image)) {
        OPanda_Leads::removeLeadField($leadId, 'externalImage');
        exit;
    }
    $image->resize($size, $size, true);
    $image->set_quality(90);
    $image->save($pathAvatar);
    $imageSource = OPanda_Leads::updateLeadField($leadId, '_image' . $size, $leadId . 'x' . $size . '.jpeg');
    $image->stream();
    exit;
}
コード例 #28
0
function get_thumb($src_url = '', $width = null, $height = null, $crop = true, $cached = true)
{
    if (empty($src_url)) {
        throw new Exception('Invalid source URL');
    }
    if (empty($width)) {
        $width = get_option('thumbnail_size_w');
    }
    if (empty($height)) {
        $height = get_option('thumbnail_size_h');
    }
    $src_info = pathinfo($src_url);
    $upload_info = wp_upload_dir();
    $upload_dir = $upload_info['basedir'];
    $upload_url = $upload_info['baseurl'];
    $thumb_name = $src_info['filename'] . "_" . $width . "X" . $height . "." . $src_info['extension'];
    if (FALSE === strpos($src_url, home_url())) {
        $source_path = $upload_info['path'] . '/' . $src_info['basename'];
        $thumb_path = $upload_info['path'] . '/' . $thumb_name;
        $thumb_url = $upload_info['url'] . '/' . $thumb_name;
        if (!file_exists($source_path) && !copy($src_url, $source_path)) {
            throw new Exception('No permission on upload directory: ' . $upload_info['path']);
        }
    } else {
        // define path of image
        $rel_path = str_replace($upload_url, '', $src_url);
        $source_path = $upload_dir . $rel_path;
        $source_path_info = pathinfo($source_path);
        $thumb_path = $source_path_info['dirname'] . '/' . $thumb_name;
        $thumb_rel_path = str_replace($upload_dir, '', $thumb_path);
        $thumb_url = $upload_url . $thumb_rel_path;
    }
    if ($cached && file_exists($thumb_path)) {
        return $thumb_url;
    }
    $editor = wp_get_image_editor($source_path);
    $editor->resize($width, $height, $crop);
    $new_image_info = $editor->save($thumb_path);
    if (empty($new_image_info)) {
        throw new Exception('Failed to create thumb: ' . $thumb_path);
    }
    return $thumb_url;
}
 private static function _generate_image_size($attachment_id, $size)
 {
     $attachment = get_post($attachment_id);
     $file = self::_load_image_to_edit_path($attachment_id);
     $size_data = self::get_image_size($size);
     $metadata = wp_get_attachment_metadata($attachment_id);
     if (!$metadata || !is_array($metadata)) {
         if ($attached_file = get_post_meta($attachment_id, '_wp_attached_file', true)) {
             $upload_dir = wp_upload_dir();
             if (!function_exists('wp_generate_attachment_metadata')) {
                 require_once ABSPATH . 'wp-admin/includes/image.php';
             }
             $metadata = wp_generate_attachment_metadata($attachment_id, $upload_dir['basedir'] . DIRECTORY_SEPARATOR . $attached_file);
             if (!$metadata) {
                 return false;
             }
         } else {
             return false;
         }
     }
     if ($size && !empty($size_data) && $file && preg_match('!^image/!', get_post_mime_type($attachment)) && self::file_is_displayable_image($file)) {
         if (function_exists('wp_get_image_editor')) {
             $editor = wp_get_image_editor($file);
             if (!is_wp_error($editor) && $editor) {
                 $new_size = $editor->multi_resize(array($size => $size_data));
                 if (empty($metadata['sizes'])) {
                     $metadata['sizes'] = $new_size;
                 } else {
                     $metadata['sizes'] = array_merge($metadata['sizes'], $new_size);
                 }
             }
         } else {
             extract($size_data);
             $file_path = image_resize($file, $width, $height, $crop);
             if (!is_wp_error($file_path) && $file_path) {
                 $file = basename($file_path);
                 $metadata['sizes'][$size] = array('file' => $file, 'width' => $width, 'height' => $height);
             }
         }
         wp_update_attachment_metadata($attachment_id, $metadata);
     }
 }
コード例 #30
0
/**
 * From wp-admin/includes/image-edit.php
 */
function pte_stream_preview_image($post_id)
{
    $post = get_post($post_id);
    @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
    $img = wp_get_image_editor(_load_image_to_edit_path($post_id));
    if (is_wp_error($img)) {
        return false;
    }
    // scale the image
    $size = $img->get_size();
    $w = $size['width'];
    $h = $size['height'];
    $ratio = pte_image_get_preview_ratio($w, $h);
    $w2 = $w * $ratio;
    $h2 = $h * $ratio;
    if (is_wp_error($img->resize($w2, $h2))) {
        return false;
    }
    return wp_stream_image($img, $post->post_mime_type, $post_id);
}