Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fill image transform setting #12214

Merged
merged 42 commits into from
Feb 4, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
cc244b1
Initial support for “fill” transform parameter
brianjhanson Oct 26, 2022
467c095
Add support for `transparent` values
brianjhanson Oct 26, 2022
3a67351
Support for positioning
brianjhanson Oct 26, 2022
07d7599
Adds support for fill within the UI
brianjhanson Oct 27, 2022
2cf7b91
Add comment
brianjhanson Oct 27, 2022
52df321
Support animated gif
brianjhanson Oct 27, 2022
62a22ce
Fix types
brianjhanson Oct 27, 2022
8aa9095
Remove privacy
brianjhanson Oct 27, 2022
232b30a
Resize then fill
brianjhanson Nov 23, 2022
ff77b8e
Merge branch '4.4' into feature/dev-239-fill-image-transform-setting
brandonkelly Jan 10, 2023
9d7d47c
Refactor `scaleToFit` into `scaleToFitAndFill`
brianjhanson Jan 11, 2023
b250795
Merge branch 'feature/dev-239-fill-image-transform-setting' of github…
brianjhanson Jan 11, 2023
79ae641
Remove $position from SVG
brianjhanson Jan 11, 2023
87c5abc
Merge branch '4.4' into feature/dev-239-fill-image-transform-setting
brandonkelly Jan 30, 2023
2318b6f
Merge branch '4.4' into feature/dev-239-fill-image-transform-setting
brandonkelly Jan 30, 2023
790ff68
Update parseTransformString() for fills
brandonkelly Jan 30, 2023
6cf72ab
Bump the schema version
brandonkelly Jan 30, 2023
1cd1a9b
Do not display "transparent" in Fill Color
brianjhanson Jan 31, 2023
72b0b59
Merge branch '4.4' into feature/dev-239-fill-image-transform-setting
brandonkelly Jan 31, 2023
e1a1e16
Tighten up this regex
brandonkelly Jan 31, 2023
75fba52
Apply fill regardless of upscale setting
brianjhanson Feb 1, 2023
800c76f
Merge branch 'feature/dev-239-fill-image-transform-setting' of github…
brianjhanson Feb 1, 2023
162385e
Add new `letterbox` transform mode
brianjhanson Feb 2, 2023
29fb7ea
Update UI to handle new mode
brianjhanson Feb 2, 2023
fffe2c1
Cleanup UI
brianjhanson Feb 2, 2023
5e86abc
Add UI for “Allow Upscaling” option
brianjhanson Feb 2, 2023
32b8895
Add upscale setting to image transforms
brianjhanson Feb 2, 2023
3c1aa6d
Only use focal point for `crop` mode
brianjhanson Feb 3, 2023
d8722f3
Add translation strings
brianjhanson Feb 3, 2023
196a613
Merge branch '4.4' of github.com:craftcms/cms into feature/dev-239-fi…
brianjhanson Feb 3, 2023
f077af3
Comment cleanup
brianjhanson Feb 3, 2023
f12b320
Fix transform string parsing
brianjhanson Feb 3, 2023
169212f
Fix tests
brianjhanson Feb 3, 2023
d0f4181
Flip upscale string
brianjhanson Feb 3, 2023
adf4936
Bump the schema version
brandonkelly Feb 3, 2023
d402ee5
Merge branch '4.4' into feature/dev-239-fill-image-transform-setting
brandonkelly Feb 3, 2023
13703ff
Sort translations
brandonkelly Feb 3, 2023
281b91f
Cleanup
brandonkelly Feb 3, 2023
fab0774
Fix migration for Postgres
brianjhanson Feb 3, 2023
62164a6
Null fallbacks in case `fill` and `upscale` aren't set yet
brandonkelly Feb 4, 2023
855a18c
Merge branch 'feature/dev-239-fill-image-transform-setting' of https:…
brandonkelly Feb 4, 2023
d81e156
Update existing transforms' configs
brandonkelly Feb 4, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/base/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ abstract public function crop(int $x1, int $x2, int $y1, int $y2): self;
* @param bool $scaleIfSmaller
* @return static Self reference
*/
abstract public function scaleToFit(?int $targetWidth, ?int $targetHeight, bool $scaleIfSmaller = true): self;
abstract public function scaleToFit(?int $targetWidth, ?int $targetHeight, bool $scaleIfSmaller = true, string $position = 'center-center'): self;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing @param for $position

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also if the fill stuff is exclusive to Raster, it feels weird to have $position defined here in the base class. Maybe Raster should just be defining its own scaleToFitAndFill() method that combines scaleToFit() and setFill()?


/**
* Scale and crop image to exactly fit the specified size.
Expand Down
9 changes: 9 additions & 0 deletions src/controllers/ImageTransformsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Craft;
use craft\helpers\Image;
use craft\models\ImageTransform;
use craft\validators\ColorValidator;
use craft\web\assets\edittransform\EditTransformAsset;
use craft\web\Controller;
use yii\web\NotFoundHttpException;
Expand Down Expand Up @@ -133,6 +134,7 @@ public function actionSave(): ?Response
$transform->quality = $this->request->getBodyParam('quality') ?: null;
$transform->interlace = $this->request->getBodyParam('interlace');
$transform->format = $this->request->getBodyParam('format');
$transform->fill = $this->request->getBodyParam('fill');

if (empty($transform->format)) {
$transform->format = null;
Expand All @@ -156,6 +158,13 @@ public function actionSave(): ?Response
$errors = true;
}

$useFill = $this->request->getBodyParam('useFill');
if ($useFill && $transform->mode === 'fit') {
$transform->fill = $transform->fill ? ColorValidator::normalizeColor($transform->fill) : 'transparent';
} else {
$transform->fill = null;
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not wild about this, but I couldn't think of a better way to allow users to specify if they wanted the current behavior (image is sized proportionately to fit within a window) or the new behavior (image is placed within an area specified by the transform).

In code, the fact that fill exists tells Craft which behavior to us, but in the UI a fill is always returned, and currently there's not a difference between no fill and a transparent one.

if (!$errors) {
$success = Craft::$app->getImageTransforms()->saveTransform($transform);
} else {
Expand Down
3 changes: 2 additions & 1 deletion src/elements/Asset.php
Original file line number Diff line number Diff line change
Expand Up @@ -2586,7 +2586,8 @@ private function _dimensions(mixed $transform = null): array
$this->_height,
$transform->width,
$transform->height,
$transform->mode
$transform->mode,
$transform->fill
);
}

Expand Down
14 changes: 8 additions & 6 deletions src/helpers/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,15 @@ public static function targetDimensions(
?int $transformWidth,
?int $transformHeight,
string $mode = 'crop',
?string $fill = null,
?bool $upscale = null,
): array {
[$width, $height] = static::calculateMissingDimension($transformWidth, $transformHeight, $sourceWidth, $sourceHeight);
$factor = max($sourceWidth / $width, $sourceHeight / $height);

$imageRatio = $sourceWidth / $sourceHeight;
$transformRatio = $width / $height;

if ($upscale ?? Craft::$app->getConfig()->getGeneral()->upscaleImages) {
// Special case for 'fit' since that's the only one whose dimensions vary from the transform dimensions
if ($mode === 'fit') {
Expand All @@ -96,14 +100,12 @@ public static function targetDimensions(
return [$width, $height];
}

if ($transformWidth === null || $transformHeight === null) {
$transformRatio = $sourceWidth / $sourceHeight;
} else {
$transformRatio = $transformWidth / $transformHeight;
// When mode is `fit` with a fill provided, always use the transform size
if ($mode === 'fit' && $fill) {
return [$width, $height];
}

$imageRatio = $sourceWidth / $sourceHeight;

// When mode is `fit` (no fill provided) or the source is the same ratio as the transform
if ($mode === 'fit' || $imageRatio === $transformRatio) {
$targetWidth = min($sourceWidth, $width, (int)round($sourceWidth / $factor));
$targetHeight = min($sourceHeight, $height, (int)round($sourceHeight / $factor));
Expand Down
22 changes: 20 additions & 2 deletions src/helpers/ImageTransforms.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use craft\errors\ImageTransformException;
use craft\image\Raster;
use craft\models\ImageTransform;
use craft\validators\ColorValidator;

/**
* Image Transforms helper.
Expand All @@ -30,7 +31,7 @@ class ImageTransforms
/**
* @var string The pattern to use for matching against a transform string.
*/
public const TRANSFORM_STRING_PATTERN = '/_(?P<width>\d+|AUTO)x(?P<height>\d+|AUTO)_(?P<mode>[a-z]+)(?:_(?P<position>[a-z\-]+))?(?:_(?P<quality>\d+))?(?:_(?P<interlace>[a-z]+))?/i';
public const TRANSFORM_STRING_PATTERN = '/_(?P<width>\d+|AUTO)x(?P<height>\d+|AUTO)_(?P<mode>[a-z]+)(?:_(?P<position>[a-z\-]+))?(?:_(?P<quality>\d+))?(?:_(?P<interlace>[a-z]+))?(?:_(?P<fill>[0-9a-f]{6}|transparent))?/i';

/**
* Create an AssetImageTransform model from a string.
Expand All @@ -55,6 +56,10 @@ public static function createTransformFromString(string $transformString): Image
unset($matches['quality']);
}

if (isset($matches['fill'])) {
$fill = ColorValidator::normalizeColor($matches['fill']);
}

return Craft::createObject([
'class' => ImageTransform::class,
/** @phpstan-ignore-next-line */
Expand All @@ -65,6 +70,7 @@ public static function createTransformFromString(string $transformString): Image
'position' => $matches['position'],
'quality' => $matches['quality'] ?? null,
'interlace' => $matches['interlace'] ?? 'none',
'fill' => $fill ?? null,
'transformer' => ImageTransform::DEFAULT_TRANSFORMER,
]);
}
Expand Down Expand Up @@ -234,7 +240,8 @@ public static function getTransformString(ImageTransform $transform, bool $ignor
'_' . $transform->mode .
'_' . $transform->position .
($transform->quality ? '_' . $transform->quality : '') .
'_' . $transform->interlace;
'_' . $transform->interlace .
($transform->fill ? '_' . ltrim($transform->fill, '#') : '');
}

/**
Expand Down Expand Up @@ -266,6 +273,7 @@ public static function normalizeTransform(mixed $transform): ?ImageTransform
'parameterChangeTime',
'mode',
'position',
'fill',
'quality',
'interlace',
]);
Expand All @@ -282,6 +290,16 @@ public static function normalizeTransform(mixed $transform): ?ImageTransform
$transform['height'] = null;
}

if (!empty($transform['fill'])) {
$normalizedValue = ColorValidator::normalizeColor($transform['fill']);
if ((new ColorValidator())->validate($normalizedValue)) {
$transform['fill'] = $normalizedValue;
} else {
Craft::warning("Invalid transform fill: {$transform['fill']}", __METHOD__);
$transform['fill'] = null;
}
}

if (array_key_exists('transform', $transform)) {
$baseTransform = self::normalizeTransform(ArrayHelper::remove($transform, 'transform'));
return self::extendTransform($baseTransform, $transform);
Expand Down
85 changes: 82 additions & 3 deletions src/image/Raster.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Imagine\Image\BoxInterface;
use Imagine\Image\ImageInterface;
use Imagine\Image\Metadata\ExifMetadataReader;
use Imagine\Image\Palette\Color\ColorInterface;
use Imagine\Image\Palette\RGB;
use Imagine\Image\Point;
use Imagine\Imagick\Imagine as ImagickImagine;
Expand Down Expand Up @@ -59,9 +60,9 @@ class Raster extends Image
private int $_quality = 0;

/**
* @var AbstractImage|null
* @var ImageInterface|null
*/
private ?AbstractImage $_image = null;
private ?ImageInterface $_image = null;

/**
* @var AbstractImagine|null
Expand All @@ -78,6 +79,11 @@ class Raster extends Image
*/
private ?Font $_font = null;

/**
* @var ColorInterface|null
*/
private ?ColorInterface $_fill = null;

/**
* @inheritdoc
*/
Expand Down Expand Up @@ -234,7 +240,7 @@ public function crop(int $x1, int $x2, int $y1, int $y2): self
/**
* @inheritdoc
*/
public function scaleToFit(?int $targetWidth, ?int $targetHeight, bool $scaleIfSmaller = true): self
public function scaleToFit(?int $targetWidth, ?int $targetHeight, bool $scaleIfSmaller = true, array|string $position = 'center-center'): self
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$position has a different type declaration here than in the base class (array|string vs string).

{
$this->normalizeDimensions($targetWidth, $targetHeight);

Expand All @@ -243,11 +249,67 @@ public function scaleToFit(?int $targetWidth, ?int $targetHeight, bool $scaleIfS
if ($scaleIfSmaller || $this->getWidth() > $targetWidth || $this->getHeight() > $targetHeight) {
$factor = max($this->getWidth() / $targetWidth, $this->getHeight() / $targetHeight);
$this->resize(round($this->getWidth() / $factor), round($this->getHeight() / $factor));

if ($this->_fill) {
$this->applyFill($targetWidth, $targetHeight, $position);
}
}

return $this;
}

protected function applyFill(?int $targetWidth, ?int $targetHeight, string $position = 'center-center')
{
$box = new Box($targetWidth, $targetHeight);
$canvas = $this->_instance->create($box, $this->_fill);

[$verticalPosition, $horizontalPosition] = explode('-', $position);

switch ($verticalPosition) {
case 'top':
$y = 0;
break;
case 'bottom':
$y = ($box->getHeight() - $this->getHeight());
break;
default:
$y = ($box->getHeight() - $this->getHeight()) / 2;
break;
}

switch ($horizontalPosition) {
case 'left':
$x = 0;
break;
case 'right':
$x = ($box->getWidth() - $this->getWidth());
break;
default:
$x = ($box->getWidth() - $this->getWidth()) / 2;
break;
}

$point = new Point($x, $y);

if ($this->_isAnimated) {
$canvas->layers()->remove(0);
$this->_image->layers()->coalesce();

foreach ($this->_image->layers() as $layer) {
$newLayer = $this->_instance->create($box, $this->_fill);
$newLayer->paste($layer, $point);
$canvas->layers()->add($newLayer);

// Hopefully this doesn't take _too_ long, but it might
$this->heartbeat();
}
} else {
$canvas->paste($this->_image, $point);
}

$this->_image = $canvas;
}

/**
* @inheritdoc
*/
Expand Down Expand Up @@ -458,6 +520,23 @@ public function setInterlace(string $interlace): self
return $this;
}

/**
* Sets the fill color based on the image's palette.
*
* @param string $fill Hex color of the fill.
* @return $this Self reference
*/
public function setFill(string $fill): self
{
if ($fill === 'transparent') {
$this->_fill = $this->_image->palette()->color('#ffffff', 0);
} else {
$this->_fill = $this->_image->palette()->color($fill);
}

return $this;
}

/**
* @inheritdoc
*/
Expand Down
2 changes: 1 addition & 1 deletion src/image/Svg.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public function crop(int $x1, int $x2, int $y1, int $y2): self
/**
* @inheritdoc
*/
public function scaleToFit(?int $targetWidth, ?int $targetHeight, bool $scaleIfSmaller = true): self
public function scaleToFit(?int $targetWidth, ?int $targetHeight, bool $scaleIfSmaller = true, string $position = 'center-center'): self
{
$this->normalizeDimensions($targetWidth, $targetHeight);

Expand Down
21 changes: 13 additions & 8 deletions src/imagetransforms/ImageTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -357,21 +357,26 @@ protected function generateTransformedImage(Asset $asset, ImageTransformIndex $i
// In case this takes a while, update the timestamp so we know it's all working
$image->setHeartbeatCallback(fn() => $this->storeTransformIndexData($index));

if ($asset->getHasFocalPoint()) {
$position = $asset->getFocalPoint();
} elseif (!preg_match('/(top|center|bottom)-(left|center|right)/', $transform->position)) {
$position = 'center-center';
} else {
$position = $transform->position;
}

switch ($transform->mode) {
case 'fit':
$image->scaleToFit($transform->width, $transform->height);
if ($transform->fill && $image instanceof Raster) {
$image->setFill($transform->fill);
}

$image->scaleToFit($transform->width, $transform->height, Craft::$app->getConfig()->getGeneral()->upscaleImages, $position);
break;
case 'stretch':
$image->resize($transform->width, $transform->height);
break;
default:
if ($asset->getHasFocalPoint()) {
$position = $asset->getFocalPoint();
} elseif (!preg_match('/(top|center|bottom)-(left|center|right)/', $transform->position)) {
$position = 'center-center';
} else {
$position = $transform->position;
}
$image->scaleAndCrop($transform->width, $transform->height, Craft::$app->getConfig()->getGeneral()->upscaleImages, $position);
}

Expand Down
1 change: 1 addition & 0 deletions src/migrations/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ public function createTables(): void
'format' => $this->string(),
'quality' => $this->integer(),
'interlace' => $this->enum('interlace', ['none', 'line', 'plane', 'partition'])->notNull()->defaultValue('none'),
'fill' => $this->string(11)->null(),
brandonkelly marked this conversation as resolved.
Show resolved Hide resolved
'parameterChangeTime' => $this->dateTime(),
'dateCreated' => $this->dateTime()->notNull(),
'dateUpdated' => $this->dateTime()->notNull(),
Expand Down
32 changes: 32 additions & 0 deletions src/migrations/m221027_160703_add_image_transform_fill.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace craft\migrations;

use craft\db\Migration;
use craft\db\Table;

/**
* m221027_160703_add_image_transform_fill migration.
*/
class m221027_160703_add_image_transform_fill extends Migration
{
/**
* @inheritdoc
*/
public function safeUp(): bool
{
// Place migration code here...
$this->addColumn(Table::IMAGETRANSFORMS, 'fill', $this->string(11)->null()->after('interlace'));

return true;
}

/**
* @inheritdoc
*/
public function safeDown(): bool
{
echo "m221027_160703_add_image_transform_fill cannot be reverted.\n";
return false;
}
}
Loading