计算获得缩略图的尺寸信息
@param string $imgWidth 原图宽度
@param string $imgHeight 原图高度
@param string $thumbWidth 缩略图宽度
@param string $thumbHeight 缩略图的高度
@param string $thumbType 处理方式
@return array
559892
private function _calcThumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType)
    {
        //初始化缩略图尺寸
        $w = $thumbWidth;
        $h = $thumbHeight;

        //初始化原图尺寸
        $oldThumbWidth = $imgWidth;
        $oldThumbHeight = $imgHeight;

        // 原图比需要的缩略图还小
        if ($imgWidth <= $thumbWidth && $imgHeight <= $thumbHeight) {
            return [$imgWidth, $imgHeight, $oldThumbWidth, $oldThumbHeight];
        }

        switch ($thumbType) {
            case 1 :
                //固定宽度  高度自增
                $h = $thumbWidth / $imgWidth * $imgHeight;
                break;
            case 2 :
                //固定高度  宽度自增
                $w = $thumbHeight / $imgHeight * $imgWidth;
                break;
            case 3 :
                //固定宽度  高度裁切
                $oldThumbHeight = $imgWidth / $thumbWidth * $thumbHeight;
                break;
            case 4 :
                //固定高度  宽度裁切
                $oldThumbWidth = $imgHeight / $thumbHeight * $thumbWidth;
                break;
            case 5 :
                //缩放最大边 原图不裁切
                if (($imgWidth / $thumbWidth) > ($imgHeight / $thumbHeight)) {
                    $h = $thumbWidth / $imgWidth * $imgHeight;
                } else if (($imgWidth / $thumbWidth) < ($imgHeight / $thumbHeight)) {
                    $w = $thumbHeight / $imgHeight * $imgWidth;
                } else {
                    $w = $thumbWidth;
                    $h = $thumbHeight;
                }
                break;
            default:
                //缩略图尺寸不变，自动裁切图片
                if (($imgHeight / $thumbHeight) < ($imgWidth / $thumbWidth)) {
                    $oldThumbWidth = $imgHeight / $thumbHeight * $thumbWidth;
                } else if (($imgHeight / $thumbHeight) > ($imgWidth / $thumbWidth)) {
                    $oldThumbHeight = $imgWidth / $thumbWidth * $thumbHeight;
                }
        }

        return [$w, $h, $oldThumbWidth, $oldThumbHeight];
    }
1190764
public function buildThumb($width = null, $height = null)
    {
        /* @var Gallery $plugin */
        $plugin = $this->getTable()->getPlugin();

        $filename = $this->getPdoValue('image');
        $thumb = PhpThumbFactory::create($plugin->getDataDir() . '/' . $filename);

        $thumb->resize(
            $width ? $width : $plugin->settings['thumbWidth'],
            $height ? $height : $plugin->settings['thumbHeight']);
        $thumb->save($plugin->getDataDir() . '/' . $this->getPdoValue('thumb'));
    }
187531
protected function generateThumbnail($thumbnailInfo, $thumbnailParams = null)
    {
        $tempFilePath = null;
        $fullThumbnailPath = null;
        $thumbnailPath = null;
        $markup = null;

        try {
            /*
             * Get and validate input data
             */
            $path = $thumbnailInfo['path'];
            $width = $thumbnailInfo['width'];
            $height = $thumbnailInfo['height'];
            $lastModified = $thumbnailInfo['lastModified'];

            if (!is_numeric($width) || !is_numeric($height) || !is_numeric($lastModified)) {
                throw new ApplicationException('Invalid input data');
            }

            if (!$thumbnailParams) {
                $thumbnailParams = $this->getThumbnailParams();
                $thumbnailParams['width'] = $width;
                $thumbnailParams['height'] = $height;
            }

            $thumbnailPath = $this->getThumbnailImagePath($thumbnailParams, $path, $lastModified);
            $fullThumbnailPath = temp_path(ltrim($thumbnailPath, '/'));

            /*
             * Save the file locally
             */
            $library = MediaLibrary::instance();
            $tempFilePath = $this->getLocalTempFilePath($path);

            if (!@File::put($tempFilePath, $library->get($path))) {
                throw new SystemException('Error saving remote file to a temporary location');
            }

            /*
             * Resize the thumbnail and save to the thumbnails directory
             */
            $this->resizeImage($fullThumbnailPath, $thumbnailParams, $tempFilePath);

            /*
             * Delete the temporary file
             */
            File::delete($tempFilePath);
            $markup = $this->makePartial('thumbnail-image', [
                'isError' => false,
                'imageUrl' => $this->getThumbnailImageUrl($thumbnailPath)
            ]);
        }
        catch (Exception $ex) {
            if ($tempFilePath) {
                File::delete($tempFilePath);
            }

            if ($fullThumbnailPath) {
                $this->copyBrokenImage($fullThumbnailPath);
            }

            $markup = $this->makePartial('thumbnail-image', ['isError' => true]);

            /*
             * @todo We need to log all types of exceptions here
             */
            traceLog($ex->getMessage());
        }

        if ($markup && ($id = $thumbnailInfo['id'])) {
            return [
                'id' => $id,
                'markup' => $markup
            ];
        }
    }
876501
public function watermark($img, $outPath = '', $pos = '', $waterImg = '', $alpha = '', $text = '')
    {
        // 验证原图像 和 是否已有错误
        if (false === $this->_checkImage($img) || $this->hasError()) {
            return $this;
        }

        $imgInfo = pathinfo($img);
        $imgType = $this->_handleImageType($imgInfo['extension']);
        $outPath = $outPath ?: ($this->waterOptions['path'] ?: \dirname($img));
        $pos = $pos ?: $this->waterOptions['pos'];
        $alpha = $alpha ?: $this->waterOptions['alpha'];
        $waterImg = $waterImg ?: $this->waterOptions['img'];
        $waterImgType = $resWaterImg = null;

        list($imgWidth, $imgHeight) = getimagesize($img);

        if ($waterImg) {

            // 验证水印图像
            if (false === $this->_checkImage($waterImg)) {
                return $this;
            }

            $waterImgType = $this->_handleImageType(pathinfo($waterImg, PATHINFO_EXTENSION));
            list($waterWidth, $waterHeight) = getimagesize($waterImg);

            if ($imgHeight < $waterHeight || $imgWidth < $waterWidth) {
                $this->_error = 'The image is too small.';

                return $this;
            }

            // create water image resource
            $resWaterImg = \call_user_func("imagecreatefrom{$waterImgType}", $waterImg);
        } else {
            //水印文字
            $text = $text ?: $this->waterOptions['text'];

            if (!is_file($this->waterOptions['fontFile'])) {
                throw new InvalidConfigException('请配置正确的水印文字资源路径');
            }

            if (!$text || \strlen($this->waterOptions['fontColor']) !== 6) {
                throw new InvalidConfigException('The watermark font color length must equal to 6.');
            }

            $textInfo = imagettfbbox($this->waterOptions['fontSize'], 0, $this->waterOptions['fontFile'], $text);
            $waterWidth = $textInfo[2] - $textInfo[6];
            $waterHeight = $textInfo[3] - $textInfo[7];
        }

        // create image resource 建立原图资源
        $method = "imagecreatefrom{$imgType}";
        $resImg = $method($img);

        //水印位置处理
        list($x, $y) = $this->_calcWaterCoords($pos, $imgWidth, $waterWidth, $imgHeight, $waterHeight);

        if ($waterImg && $resWaterImg && $waterImgType) {

            // is png image. 'IMAGETYPE_PNG' === 3
            if ($waterImgType === self::IMAGE_PNG) {
                imagecopy($resImg, $resWaterImg, $x, $y, 0, 0, $waterWidth, $waterHeight);
            } else {
                imagecopymerge($resImg, $resWaterImg, $x, $y, 0, 0, $waterWidth, $waterHeight, $alpha);
            }
        } else {
            $r = hexdec(substr($this->waterOptions['fontColor'], 0, 2));
            $g = hexdec(substr($this->waterOptions['fontColor'], 2, 2));
            $b = hexdec(substr($this->waterOptions['fontColor'], 4, 2));
            $color = imagecolorallocate($resImg, $r, $g, $b);
            $charset = 'UTF-8';

            imagettftext(
                $resImg, $this->waterOptions['fontSize'], 0, $x, $y,
                $color, $this->waterOptions['fontFile'], iconv($charset, 'utf-8', $text)
            );
        }

        if (!Directory::create($outPath)) {
            $this->_error = 'Failed to create the output directory path!. OUT-PATH: ' . $outPath;

            return $this;
        }

        $outFile = $outPath . '/' . $imgInfo['basename'];

        if ($imgType === self::IMAGE_JPEG) {
            imagejpeg($resImg, $outFile, $this->waterOptions['quality']);
        } elseif ($imgType === self::IMAGE_PNG) {
            imagepng($resImg, $outFile, ceil($this->waterOptions['quality'] / 10));
        } else {
            \call_user_func("image{$imgType}", $resImg, $outFile);
        }

        imagedestroy($resImg);

        $this->working = [
            'raw' => $img,
            'out' => $outFile,
        ];

        $this->_result['workWater']['rawFile'] = $img;
        $this->_result['workWater']['outFile'] = $outFile;

        return $this;
    }
573202
public static function thumbImg($srcfile, $dstfile, $thumbWidth, $thumbHeight)
    {
        $imageinfo = getimagesize($srcfile);
        if (empty($imageinfo)) {
            throw_error('只支持gif,jpg,png的图片');
        }

        // dd($imageinfo);

        if ($imageinfo[2] == 1) {
            $im = imagecreatefromgif($srcfile);
        } elseif ($imageinfo[2] == 2) {
            $im = imagecreatefromjpeg($srcfile);
        } elseif ($imageinfo[2] == 3) {
            $im = imagecreatefrompng($srcfile);
        } else {
            throw_error('只支持gif,jpg,png的图片');
        }

        $w = $imageinfo[0];
        $h = $imageinfo[1];

        if ($thumbWidth / $thumbHeight > $w / $h) {
            $nh = $thumbHeight;
            $nw = ($w * $thumbHeight) / $h;
        } else {
            $nw = $thumbWidth;
            $nh = ($h * $thumbWidth) / $w;
        }
        // echo "w: $nw , h: $nh";exit;

        $ni = imagecreatetruecolor($nw, $nh);
        imagecopyresampled($ni, $im, 0, 0, 0, 0, $nw, $nh, $w, $h);
        imagejpeg($ni, $dstfile);
        imagedestroy($im);

        return file_exists($dstfile);
    }
768871
public static function is_size_for_post_type( $img_size, $attachment_post_type ) {
		if ( ! is_array( $attachment_post_type ) ) {
			$attachment_post_type = array( $attachment_post_type );
		}

		// Reset post types that should be applied as a standard
		$post_types_to_apply = array( '', 'page', 'post' );

		/**
		 * When a post type is given in the arguments, we generate the size
		 * only if the attachment is associated with that post.
		 */
		if ( array_key_exists( 'post_types', $img_size ) ) {
			$post_types_to_apply = $img_size['post_types'];
		}

		if ( ! in_array( 'all', $post_types_to_apply, true ) ) {
			// Check if we should really resize that picture
			$intersections = array_intersect( $post_types_to_apply, $attachment_post_type );

			if ( ! empty( $intersections ) ) {
				return true;
			}
		} else {
			return true;
		}

		return false;
	}
365607
public function thumb(string $src, string $dst, integer $width, integer $height)
    {
        $anchor='center';
        return $this
        ->image($src)
        ->thumbnail($width, $height, $anchor)
        ->toFile($dst);
    }
912704
function getPopupImgPos (imgWidth, imgHeight) {
  let viewportW = viewport.getWidth()
  let viewportH = viewport.getHeight()
  let top = 0
  let left = 0
  if (viewportH / viewportW < imgHeight / imgWidth) {
    let width = Math.round(viewportH * imgWidth / imgHeight)
    left = (viewportW - width) / 2
    return {
      height: viewportH,
      width,
      left,
      top: 0
    }
  }
  let height = Math.round(viewportW * imgHeight / imgWidth)
  top = (viewportH - height) / 2
  return {
    height,
    width: viewportW,
    left: 0,
    top
  }
}
91312
public function get_thumb_url($image_url, $orig_width, $orig_height, $thumb_width = 75, $force = false) {
        global $OUTPUT;

        if (!$force && $orig_width <= $thumb_width && $orig_height <= $thumb_width) {
            return $image_url;
        } else {
            $thumb_url = '';
            $commons_main_dir = 'https://upload.wikimedia.org/wikipedia/commons/';
            if ($image_url) {
                $short_path = str_replace($commons_main_dir, '', $image_url);
                $extension = strtolower(pathinfo($short_path, PATHINFO_EXTENSION));
                if (strcmp($extension, 'gif') == 0) {  //no thumb for gifs
                    return $OUTPUT->image_url(file_extension_icon('.gif', $thumb_width))->out(false);
                }
                $dir_parts = explode('/', $short_path);
                $file_name = end($dir_parts);
                if ($orig_height > $orig_width) {
                    $thumb_width = round($thumb_width * $orig_width/$orig_height);
                }
                $thumb_url = $commons_main_dir . 'thumb/' . implode('/', $dir_parts) . '/'. $thumb_width .'px-' . $file_name;
                if (strcmp($extension, 'svg') == 0) {  //png thumb for svg-s
                    $thumb_url .= '.png';
                }
            }
            return $thumb_url;
        }
    }
795007
private static int getTrimmedWidth(BufferedImage img) {
    int height = img.getHeight();
    int width = img.getWidth();
    int trimmedWidth = 0;

    for (int i = 0; i < height; i++) {
      for (int j = width - 1; j >= 0; j--) {
        if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {
          trimmedWidth = j;
          break;
        }
      }
    }

    return trimmedWidth;
  }
423110
private static function getImageSize($img)
    {
        $width  = imagesx($img);
        $height = imagesy($img);
        if ( ! $width || ! $height) {
            throw new \Exception('can`t create thumbnail: can`t get image size, invalid image width or height');
        }

        return [$width, $height];
    }
271549
protected function image($type, $thumb, $name, $func = null)
    {
        $func = strtolower(__FUNCTION__.$type);
        $rootPath = $this->rootDir.DS.str_replace(['/', '\\'], DS, $this->thumbPath).$name;
        /** @var $func TYPE_NAME */
        //if (is_callable($func)) {
        if (!$func($thumb, $rootPath)) {
            throw new \Exception('Unknown Exception while generating thumb image');
        }

        chmod($rootPath, 0777);
    }
1008642
private ByteArrayInputStream generateThumbImageStream(InputStream inputStream,
                                                          ThumbImage thumbImage) throws IOException {
        //根据传入配置生成缩略图
        if (thumbImage.isDefaultConfig()) {
            //在中间修改配置，这里不是一个很好的实践，如果有时间再进行优化
            thumbImage.setDefaultSize(thumbImageConfig.getWidth(), thumbImageConfig.getHeight());
            return generateThumbImageByDefault(inputStream);
        } else if (thumbImage.getPercent() != 0) {
            return generateThumbImageByPercent(inputStream, thumbImage);
        } else {
            return generateThumbImageBySize(inputStream, thumbImage);
        }

    }
1280903
public function getThumbnail(int $size = 210, bool $ssl = false)
    {
        $thumbs = [];
        foreach ($this->safeGet('thumbnail') as $thumb) {
            $thumbs[$thumb['width']] = $thumb['_link'];
        }

        $sizes = array_keys($thumbs);
        while (true) {
            $thumbSize = array_shift($sizes);
            if ((int) $size <= (int) $thumbSize || count($sizes) === 0) {
                return $thumbs[$thumbSize];
            }
        }
    }
88062
public static function makeThumbnail($uploadDir, $image, $thumbnailPath, $thumbnailWords)
    {
        $thumbnailWidth = 50;
        $thumbnailHeight = 50;
        $arrayImageDetail = getimagesize("$uploadDir"."$image");
        $originalWidth = $arrayImageDetail[0];
        $originalHeight = $arrayImageDetail[1];

        if ($originalWidth > $originalHeight) {
            $newWidth = $thumbnailWidth;
            $newHeight = intval($originalHeight * $newWidth / $originalWidth);
        } else {
            $newHeight = $thumbnailHeight;
            $newWidth = intval($originalWidth * $newHeight / $originalHeight);
        }

        $varX = intval(($thumbnailWidth - $newWidth) / 2);
        $varY = intval(($thumbnailHeight - $newHeight) / 2);

        if ($arrayImageDetail[2] == 1) {
            $imageType = "ImageGIF";
            $createFrom = "ImageCreateFromGIF";
        } elseif ($arrayImageDetail[2] == 2) {
            $imageType = "ImageJPEG";
            $createFrom = "ImageCreateFromJPEG";
        } elseif ($arrayImageDetail[2] == 3) {
            $imageType = "ImagePNG";
            $createFrom = "ImageCreateFromPNG";
        }

        if ($imageType) {
            $oldImage = $createFrom("$uploadDir"."$image");
            $newImage = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);
            imagecopyresized($newImage, $oldImage, $varX, $varY, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
            $imageType($newImage, "$thumbnailPath"."$thumbnailWords".'_'."$image");
        }

        return "$thumbnailWords".'_'."$image";
    }
388795
protected function getCenterOffset(\Imagick $image, $targetWidth, $targetHeight)
    {
        $size = $image->getImageGeometry();
        $originalWidth = $size['width'];
        $originalHeight = $size['height'];
        $goalX = (int) (($originalWidth-$targetWidth)/2);
        $goalY = (int) (($originalHeight-$targetHeight)/2);

        return array('x' => $goalX, 'y' => $goalY);
    }
397061
protected function checkSize($imagick)
    {
        $width = $imagick->getImageWidth();
        if ($width > self::MAX_RECOMMENDED_IMAGE_WIDTH) {
            $this->logger->warning(sprintf(
                _('画像の幅は %1$s 以下にすべきです。「%2$s」の幅は %3$s です。'),
                self::MAX_RECOMMENDED_IMAGE_WIDTH . 'px',
                $this->filename,
                $width . 'px'
            ));
        }

        $height = $imagick->getImageHeight();
        if ($height > self::MAX_RECOMMENDED_IMAGE_HEIGHT) {
            $this->logger->warning(sprintf(
                _('画像の高さは %1$s 以下にすべきです。「%2$s」の高さは %3$s です。'),
                self::MAX_RECOMMENDED_IMAGE_HEIGHT . 'px',
                $this->filename,
                $height . 'px'
            ));
        }
    }