不裁剪方式生成缩略图

@param int $thumbWidth
@param int $thumbHeight
@return bool | string
@throws \wf\image\Exception
767631
private function thumbUnCut($thumbWidth, $thumbHeight, $quality, $thumbType = 'jpg') 
    {
        list($srcW, $srcH) = $this->imgInfo;
        
        // 宽或高按比例缩放
        if ($thumbWidth == 0 || $thumbHeight == 0) {
            if ($thumbWidth == 0) {
                $thumbHeight = $srcH * ($thumbWidth / $srcW);
            } else {
                $thumbWidth = $thumbWidth = $srcW * ($thumbHeight/$srcH);
            }
            $imgW = $thumbWidth; // 图片显示宽
            $imgH = $thumbHeight; // 图片显示高
            $posX = 0; 
            $posY = 0;
        } else {
            if ($thumbWidth/$thumbHeight < $srcW/$srcH) {
                // 宽比例超过，补上高
                $imgW = $thumbWidth; // 图片显示宽
                $imgH = $thumbWidth * $srcH / $srcW; // 图片显示高
                $posX = 0;
                $posY = ($thumbHeight - $imgH) / 2;
            } else {
                // 高比例超过，补上宽
                $imgH = $thumbHeight; // 图片显示宽
                $imgW = $thumbHeight * $srcW / $srcH; // 图片显示高
                $posX = ($thumbWidth - $imgW) / 2;
                $posY = 0;
            }
        }
        
        $thumbImage = imagecreate($thumbWidth, $thumbHeight);
        
        // 填充背景色
        $fillColor = imagecolorallocate($thumbImage, $this->bgColor[0], $this->bgColor[1], $this->bgColor[2]);
        imagefill($thumbImage, 0, 0, $fillColor);

        // 合上图
        $attachImage = imagecreatefromstring($this->imageContent);
        imagecopyresized($thumbImage, $attachImage, $posX, $posY, 0, 0, $imgW, $imgH, $srcW, $srcH);
        
        // 为兼容云存贮设备，不直接把缩略图写入文件系统，而是返回文件内容
        ob_start();

        if ($thumbType == 'webp') {
            imagewebp($thumbImage, null, $quality);
        } elseif ($thumbType == 'png') {
            imagepng($thumbImage, null, floor($quality/10));
        } else {
            imagejpeg($thumbImage, null, $quality);
        }

        $thumb = ob_get_clean();

        imagedestroy($attachImage);
        imagedestroy($thumbImage);
        
        if(!$thumb) {
            throw new Exception('无法生成缩略图');
        }
        
        return $thumb;
    }
1294263
public function changeDimensions($sourceImage, $desiredWidth, $desiredHeight)
    {
        $temp = '';
        // find the height and width of the image
        if (imagesx($sourceImage) >= imagesy($sourceImage)
            && imagesx($sourceImage) >= $this->fixedWidth
        ) {
            $temp = imagesx($sourceImage) / $this->fixedWidth;
            $desiredWidth = imagesx($sourceImage) / $temp;
            $desiredHeight = imagesy($sourceImage) / $temp;
        } elseif (imagesx($sourceImage) <= imagesy($sourceImage)
            && imagesy($sourceImage) >= $this->fixedHeight
        ) {
            $temp = imagesy($sourceImage) / $this->fixedHeight;
            $desiredWidth = imagesx($sourceImage) / $temp;
            $desiredHeight = imagesy($sourceImage) / $temp;
        } else {
            $desiredWidth = imagesx($sourceImage);
            $desiredHeight = imagesy($sourceImage);
        }

        // create a new image
        $thumbImg = imagecreatetruecolor($desiredWidth, $desiredHeight);
        $imgAllocate = imagecolorallocate($thumbImg, 255, 255, 255);
        imagefill($thumbImg, 0, 0, $imgAllocate);

        //copy source image to resize
        imagecopyresampled(
            $thumbImg,
            $sourceImage,
            0,
            0,
            0,
            0,
            $desiredWidth,
            $desiredHeight,
            imagesx($sourceImage),
            imagesy($sourceImage)
        );

        return $thumbImg;
    }
1245403
private ByteArrayInputStream generateThumbImageBySize(InputStream inputStream,
                                                          ThumbImage thumbImage) throws IOException {
        LOGGER.debug("根据传入尺寸生成缩略图");
        // 在内存当中生成缩略图
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //@formatter:off
        Thumbnails
                .of(inputStream)
                .size(thumbImage.getWidth(), thumbImage.getHeight())
                .toOutputStream(out);
        //@formatter:on
        return new ByteArrayInputStream(out.toByteArray());
    }
1028536
public function createThumb($imageObj, $width = null, $height = null, array $options = [])
    {
        $extension = File::extension($imageObj->url);
        $basePath = base_path('/');

        if(!is_numeric($width)) {
            throw new \Exception("Width must be a number");
        }

        if ($this->hasImageExtension($extension)) {

            //thumb can only be created if original source exist
            if(file_exists($basePath.$imageObj->url) && File::size($basePath.$imageObj->url)) {

                $thumbDir = base_path($imageObj->fileDirectory . "/" . $width.($height ? 'x'.$height : ""));

                if (!File::exists($thumbDir)) {
                    if (!File::makeDirectory($thumbDir, 0700, true)) {
                        throw new \Exception("Could not create thumb directory '".$thumbDir."'. Please check permissions.");
                    }
                }

                //check if paths are writable
                if (!File::isWritable($thumbDir)) {
                    throw new \Exception("Thumb could not be created because the directory '".$thumbDir."' is not writable!. Please check permissions.");
                }

                //create thumb
                $img = Image::make(base_path($imageObj->url));

                // crop with and height
                if($width && $height) {
                    if (isset($options['resizeCanvas']) && $options['resizeCanvas'] === true) {
                        $img->resize(
                            $width, $height, function ($constraint) {
                                $constraint->aspectRatio();
                            }
                        )->resizeCanvas($width, $height);
                    } else {
                        $img->fit($width, $height);
                    }
                }elseif($width) { // resize only the width of the image
                    $img->resize(
                        $width, null, function ($constraint) {
                            $constraint->aspectRatio();
                        }
                    );
                }
                elseif($height) { // resize only the height of the image
                    $img->resize(
                        null, $height, function ($constraint) {
                            $constraint->aspectRatio();
                        }
                    );
                }

                if ($img->save($thumbDir . '/' . $imageObj->filename, config('image-optimizer.default_quality'))) {
                    // optimize image
                    $this->optimize($thumbDir . '/' . $imageObj->filename);
                    return true;
                }
            }
        }
        return false;
    }
968026
public function isPermittedDimension($iWidth, $iHeight): bool
    {
        if (Factory::property('allowDangerousImageTransformation', 'nails/module-cdn')) {
            return true;
        } else {
            $sDimension = $iWidth . 'x' . $iHeight;
            return in_array($sDimension, $this->aPermittedDimensions);
        }
    }
187279
public function setThumbnail($thumbnail, $height = null, $weight = null)
    {
        self::$xml['thumbnail'] = '<media:thumbnail';
        $this->setThumbnailUrl($thumbnail);

        if (null !== $height) {
            $this->setThumbnailHeight($height);
        }

        if (null !== $weight) {
            $this->setThumbnailWidth($weight);
        }

        self::$xml['thumbnail'] .= '/>';

        return $this;
    }
1051711
public function show($sString, $iWidth = null, $iHeight = null)
    {
        $rImg = $this->generateBarcode($sString, $iWidth, $iHeight);

        if ($rImg) {

            header('Content-Type: image/png');
            imagepng($rImg);
            imagedestroy($rImg);
            exit(0);

        } else {

            return false;
        }
    }
1342116
public function thumb($width, $height, $type = Image::IMAGE_THUMB_SCALE){
        if(empty($this->img)) E('没有可以被缩略的图像资源');

        //原图宽度和高度
        $w = $this->info['width'];
        $h = $this->info['height'];

        /* 计算缩略图生成的必要参数 */
        switch ($type) {
            /* 等比例缩放 */
            case Image::IMAGE_THUMB_SCALE:
                //原图尺寸小于缩略图尺寸则不进行缩略
                if($w < $width && $h < $height) return;

                //计算缩放比例
                $scale = min($width/$w, $height/$h);
                
                //设置缩略图的坐标及宽度和高度
                $x = $y = 0;
                $width  = $w * $scale;
                $height = $h * $scale;
                break;

            /* 居中裁剪 */
            case Image::IMAGE_THUMB_CENTER:
                //计算缩放比例
                $scale = max($width/$w, $height/$h);

                //设置缩略图的坐标及宽度和高度
                $w = $width/$scale;
                $h = $height/$scale;
                $x = ($this->info['width'] - $w)/2;
                $y = ($this->info['height'] - $h)/2;
                break;

            /* 左上角裁剪 */
            case Image::IMAGE_THUMB_NORTHWEST:
                //计算缩放比例
                $scale = max($width/$w, $height/$h);

                //设置缩略图的坐标及宽度和高度
                $x = $y = 0;
                $w = $width/$scale;
                $h = $height/$scale;
                break;

            /* 右下角裁剪 */
            case Image::IMAGE_THUMB_SOUTHEAST:
                //计算缩放比例
                $scale = max($width/$w, $height/$h);

                //设置缩略图的坐标及宽度和高度
                $w = $width/$scale;
                $h = $height/$scale;
                $x = $this->info['width'] - $w;
                $y = $this->info['height'] - $h;
                break;

            /* 填充 */
            case Image::IMAGE_THUMB_FILLED:
                //计算缩放比例
                if($w < $width && $h < $height){
                    $scale = 1;
                } else {
                    $scale = min($width/$w, $height/$h);
                }

                //设置缩略图的坐标及宽度和高度
                $neww = $w * $scale;
                $newh = $h * $scale;
                $posx = ($width  - $w * $scale)/2;
                $posy = ($height - $h * $scale)/2;

                do{
                    //创建新图像
                    $img = imagecreatetruecolor($width, $height);
                    // 调整默认颜色
                    $color = imagecolorallocate($img, 255, 255, 255);
                    imagefill($img, 0, 0, $color);

                    //裁剪
                    imagecopyresampled($img, $this->img, $posx, $posy, $x, $y, $neww, $newh, $w, $h);
                    imagedestroy($this->img); //销毁原图
                    $this->img = $img;
                } while(!empty($this->gif) && $this->gifNext());
                
                $this->info['width']  = $width;
                $this->info['height'] = $height;
                return;

            /* 固定 */
            case Image::IMAGE_THUMB_FIXED:
                $x = $y = 0;
                break;

            default:
                E('不支持的缩略图裁剪类型');
        }

        /* 裁剪图像 */
        $this->crop($w, $h, $x, $y, $width, $height);
    }
1253135
public ThumborUrlBuilder resize(int width, int height) {
    if (width < 0 && width != ORIGINAL_SIZE) {
      throw new IllegalArgumentException("Width must be a positive number.");
    }
    if (height < 0 && height != ORIGINAL_SIZE) {
      throw new IllegalArgumentException("Height must be a positive number.");
    }
    if (width == 0 && height == 0) {
      throw new IllegalArgumentException("Both width and height must not be zero.");
    }
    hasResize = true;
    resizeWidth = width;
    resizeHeight = height;
    return this;
  }
10381
public function size(Int $width, Int $height) : Thumb
    {
        $this->sets['width']  = $width;
        $this->sets['height'] = $height;

        return $this;
    }
1030828
public function thumb($output, $thumbWidth = 0, $thumbHeight = 0, $auto = true){
		$width = $this->getWidth();
		$height = $this->getHeight();
		if ($thumbWidth <= 0) {
			$thumbWidth = $auto ? ($thumbHeight / $height * $width) : $width;
		} elseif ($thumbHeight <= 0) {
			$thumbHeight = $auto ? ($thumbWidth / $width * $height) : $height;
		} elseif($auto) {
			$rate = min($height / $thumbHeight, $width / $thumbWidth);
			$width = $thumbWidth * $rate;
			$height = $thumbHeight * $rate;
		}
		
		$thumb = new Image();
		$thumb->create($thumbWidth, $thumbHeight);
		$thumb->copyFromWithResize($this, 0, 0, 0, 0, $width, $height);
		$thumb->saveAs($output);
		$thumb->close();
		return $output;
	}
836369
def __make_thumbnail(self, width, height):
        
        (w, h) = self.size
        factor = max(
            (float(w) / width),
            (float(h) / height)
        )
        w /= factor
        h /= factor
        return self.get_image((round(w), round(h)))
1059363
public function thumbnail($image, $targetWidth = 100, $targetHeight = 100)
    {
        $imagePath = $this->container->getParameter('red_kite_cms.web_folder_full_path') . $image;
        if (!is_file($imagePath)) {
            return null;
        }
        $thumbnailer = $this->container->get('red_kite_cms.images_thumbnailer');
        $thumbnailer->create($imagePath, $targetWidth, $targetHeight);

        return sprintf('<img src="%s" width="%s" height="%s" rel="%s" />', dirname($image) .  '/' . $thumbnailer->getThumbnailFolder() . '/' . $thumbnailer->getThumbnailImageName(), $thumbnailer->getThumbnailWidth(), $thumbnailer->getThumbnailHeight(), $image);
    }
196969
private ByteArrayInputStream generateThumbImageByPercent(InputStream inputStream,
                                                             ThumbImage thumbImage) throws IOException {
        LOGGER.debug("根据传入比例生成缩略图");
        // 在内存当中生成缩略图
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //@formatter:off
        Thumbnails
                .of(inputStream)
                .scale(thumbImage.getPercent())
                .toOutputStream(out);
        //@formatter:on
        return new ByteArrayInputStream(out.toByteArray());
    }
676150
public function base64($sString, $iWidth = null, $iHeight = null)
    {
        $rImg = $this->generateBarcode($sString, $iWidth, $iHeight);

        if ($rImg) {

            ob_start();
            imagepng($rImg);
            $sContents = ob_get_contents();
            ob_end_clean();

            return base64_encode($sContents);

        } else {

            return false;
        }
    }
421878
protected function createThumbnail($imagePath, $thumbnailPath) {
        if ($this->config['images']['thumbnail']['enabled'] === true) {
            Log::info('generating thumbnail "' . $thumbnailPath . '"');

            // create folder if it does not exist
            if (!file_exists(dirname($thumbnailPath))) {
                mkdir(dirname($thumbnailPath), 0755, true);
            }

            $this->initUploader([
                'upload_dir' => dirname($imagePath) . '/',
            ])->create_thumbnail_image($imagePath);
        }
    }
978658
private function getSizeByAuto($newWidth, $newHeight)
		# Author:     Jarrod Oberto
		# Date:       19-08-08
		# Purpose:    Depending on the height, choose to resize by 0, 1, or 2
		# Param in:   The new height and new width
		# Notes:
		#
	{
		// *** If forcing is off...
		if ( ! $this->forceStretch)
		{

			// *** ...check if actual size is less than target size
			if ($this->width < $newWidth && $this->height < $newHeight)
			{
				return array( 'optimalWidth' => $this->width, 'optimalHeight' => $this->height );
			}
		}

		if ($this->height < $this->width)
			// *** Image to be resized is wider (landscape)
		{
			//$optimalWidth = $newWidth;
			//$optimalHeight= $this->getSizeByFixedWidth($newWidth);

			$dimensionsArray = $this->getSizeByFixedWidth($newWidth, $newHeight);
			$optimalWidth = $dimensionsArray['optimalWidth'];
			$optimalHeight = $dimensionsArray['optimalHeight'];
		}
		elseif ($this->height > $this->width)
			// *** Image to be resized is taller (portrait)
		{
			//$optimalWidth = $this->getSizeByFixedHeight($newHeight);
			//$optimalHeight= $newHeight;

			$dimensionsArray = $this->getSizeByFixedHeight($newWidth, $newHeight);
			$optimalWidth = $dimensionsArray['optimalWidth'];
			$optimalHeight = $dimensionsArray['optimalHeight'];
		}
		else
			// *** Image to be resizerd is a square
		{

			if ($newHeight < $newWidth)
			{
				//$optimalWidth = $newWidth;
				//$optimalHeight= $this->getSizeByFixedWidth($newWidth);
				$dimensionsArray = $this->getSizeByFixedWidth($newWidth, $newHeight);
				$optimalWidth = $dimensionsArray['optimalWidth'];
				$optimalHeight = $dimensionsArray['optimalHeight'];
			}
			else
			{
				if ($newHeight > $newWidth)
				{
					//$optimalWidth = $this->getSizeByFixedHeight($newHeight);
					//$optimalHeight= $newHeight;
					$dimensionsArray = $this->getSizeByFixedHeight($newWidth, $newHeight);
					$optimalWidth = $dimensionsArray['optimalWidth'];
					$optimalHeight = $dimensionsArray['optimalHeight'];
				}
				else
				{
					// *** Sqaure being resized to a square
					$optimalWidth = $newWidth;
					$optimalHeight = $newHeight;
				}
			}
		}

		return array( 'optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight );
	}