3

我在 yii2 中得到了这个代码:

Image::thumbnail($path, 100, 100)->save($thumbnail, ['quality' => 50]);

我认为它会调整原始图像的大小,保持纵横比。但它只是创建了一个盒子......有什么问题吗?

4

3 回答 3

6

你可以这样使用:

use Imagine\Image\Box;

Image::frame($path)
->thumbnail(new Box(100, 100))
->save($thumbnail, ['quality' => 50]);
于 2015-05-18T05:08:16.890 回答
1

我在 Yii2 中使用这样的,它工作正常。它还保持纵横比与宽度完美相关。

use yii\imagine\Image;
use Imagine\Image\Box;

 ...

$imagine = Image::getImagine()
->open($resizeImagePath)
->thumbnail(new Box(120, 120))
->save($thumbnailImagePath, ['quality' => 90]);
于 2015-12-15T09:11:01.533 回答
0

我编写了一个简单的代码来保持图像的纵横比。

use yii\imagine\Image;

..................................................... …………………………………………………………………………

public function doResize($imageLocation, $imageDestination, Array $options = null)
{
    $newWidth = $newHeight = 0;
    list($width, $height) = getimagesize($imageLocation);

    if(isset($options['newWidth']) || isset($options['newHeight']))
    {
        if(isset($options['newWidth']) && isset($options['newHeight']))
        {
            $newWidth = $options['newWidth'];
            $newHeight = $options['newHeight'];
        }

        else if(isset($options['newWidth']))
        {
            $deviationPercentage = (($width - $options['newWidth']) / (0.01 * $width)) / 100;

            $newWidth = $options['newWidth'];
            $newHeight = $height - ($height * $deviationPercentage);
        }

        else
        {
            $deviationPercentage = (($height - $options['newHeight']) / (0.01 * $height)) / 100;

            $newWidth = $width - ($width * $deviationPercentage);
            $newHeight = $options['newHeight'];
        }
    }

    else
    {
        // reduce image size up to 20% by default
        $reduceRatio = isset($options['reduceRatio']) ? $options['reduceRatio'] : 20;

        $newWidth = $width * ((100 - $reduceRatio) / 100);
        $newHeight = $height * ((100 - $reduceRatio) / 100);
    }

    return Image::thumbnail(
        $imageLocation, 
        (int) $newWidth, 
        (int) $newHeight
    )->save(
        $imageDestination,
        ['quality' => isset($options['quality']) ? $options['quality'] : 100]
    );
}

您可以使用它,例如:

(new TheClass)->doResize($imageLocation, $imageDestination, [
    'quality' => 70,
    'reduceRatio' => 50
]);

// or like this
(new TheClass)->doResize($imageLocation, $imageDestination, [
    'quality' => 70,
    'width' => 500,
]);

// or like this
(new TheClass)->doResize($imageLocation, $imageDestination, [
    'quality' => 70,
    'height' => 500,
]);

// and like this (but will break the aspect ratio)
(new TheClass)->doResize($imageLocation, $imageDestination, [
    'quality' => 70,
    'width' => 100
    'height' => 500,
]);
于 2016-01-31T02:19:30.067 回答