Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add sizeRounding argument to thumbnail fields, default to UP (#19913)

Lukasz Ostrowski23ee3fd5bd63
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37db715d43..faae91c5cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Breaking changes
+- Thumbnail sizes are now rounded up by default. A requested `size` that is not one of the available thumbnail sizes (32, 64, 128, 256, 512, 1024, 2048, 4096) now resolves to the smallest available size not smaller than requested (e.g. `1500` returns `2048`), instead of the nearest one (`1024`), which made images look blurry when displayed at the requested size. Pass `sizeRounding: NEAREST` to restore the previous behavior. This applies to all thumbnail fields: `User.avatar`, `Product.thumbnail`, `ProductMedia.url`, `ProductImage.url`, `OrderLine.thumbnail`, `Category.backgroundImage`, `Collection.backgroundImage`, `AppBrandLogo.default` and `AppManifestBrandLogo.default`, as well as product thumbnails in email notifications.
- Removed the deprecated Authorize.Net payment gateway plugin (`mirumee.payments.authorize_net`).
- Removed the deprecated Razorpay payment gateway plugin (`mirumee.payments.razorpay`).
- Removed the deprecated Braintree payment gateway plugin (`mirumee.payments.braintree`).
diff --git a/docs/adr/0011-thumbnail-size-rounds-up-by-default.md b/docs/adr/0011-thumbnail-size-rounds-up-by-default.md
new file mode 100644
index 0000000000..c02a1e1012
--- /dev/null
+++ b/docs/adr/0011-thumbnail-size-rounds-up-by-default.md
@@ -0,0 +1,19 @@
+# Thumbnail size rounds up by default
+
+**Tags:** thumbnail, graphql, breaking change
+
+Thumbnails exist only in a fixed set of sizes (32 to 4096, doubling). A requested `size` that is
+not one of them has to be matched to one, and the `sizeRounding` argument on thumbnail fields
+chooses how: `NEAREST` picks the closest size, `UP` the smallest size not smaller than requested.
+
+From Saleor 3.24 the default is `UP`; `NEAREST` is opt-in. We trade image quality for client
+performance: `NEAREST` can return fewer pixels than requested (`1500` gives `1024`), and the
+browser stretches the image to fill its slot, which looks blurry. Merchants reported this as a
+Saleor bug, not as a mistake in the size they asked for. `UP` never returns fewer pixels than
+requested, so a client asking for the size it displays gets a sharp image. The cost is bandwidth:
+in the worst case (`1025` gives `2048`) the image has four times the pixels. Clients that care
+more about bytes than sharpness can pass `NEAREST`.
+
+`sizeRounding` was introduced in 3.23 with `NEAREST` as the default, because changing what an
+existing query returns in a patch release is a breaking change. 3.23 lets clients opt in to `UP`;
+3.24 flips the default and lets them opt back out.
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 230f6a78f7..2168633c5a 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -22,6 +22,7 @@ from ...permission.enums import (
)
from ...permission.utils import one_of_permissions_or_auth_filter_required
from ...plugins.manager import PluginsManager
+from ...thumbnail import ThumbnailSizeRounding
from ...thumbnail.utils import (
get_image_or_proxy_url,
get_thumbnail_format,
@@ -901,6 +902,7 @@ class User(ModelObjectType[models.User]):
root: models.User,
info: ResolveInfo,
size: int | None = None,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
) -> None | Image | Promise[Image]:
if not root.avatar:
@@ -910,7 +912,7 @@ class User(ModelObjectType[models.User]):
return Image(url=root.avatar.url, alt=None)
format = get_thumbnail_format(format)
- selected_size = get_thumbnail_size(size)
+ selected_size = get_thumbnail_size(size, size_rounding)
def _resolve_avatar(thumbnail):
url = get_image_or_proxy_url(
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index 216f17de76..5c5c6540a2 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -15,7 +15,7 @@ from ...core.utils import build_absolute_uri
from ...permission.auth_filters import AuthorizationFilters, is_staff_user
from ...permission.enums import AccountPermissions, AppPermission
from ...permission.utils import message_one_of_permissions_required
-from ...thumbnail import PIL_IDENTIFIER_TO_MIME_TYPE
+from ...thumbnail import PIL_IDENTIFIER_TO_MIME_TYPE, ThumbnailSizeRounding
from ...thumbnail.utils import (
ProcessedIconImage,
get_icon_thumbnail_format,
@@ -350,6 +350,7 @@ class AppManifestBrandLogo(BaseObjectType):
_info: ResolveInfo,
*,
size: int | None = None,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
):
format = get_icon_thumbnail_format(format)
@@ -357,7 +358,7 @@ class AppManifestBrandLogo(BaseObjectType):
# as text and used for preview purposes only
if size == 0:
size = MANIFEST_THUMBNAIL_MAX_SIZE
- size = min(get_thumbnail_size(size), MANIFEST_THUMBNAIL_MAX_SIZE)
+ size = min(get_thumbnail_size(size, size_rounding), MANIFEST_THUMBNAIL_MAX_SIZE)
logo_img = root["default"]
# prepare thumbnail on the fly
@@ -386,6 +387,7 @@ class AppBrandLogo(BaseObjectType):
info: ResolveInfo,
*,
size: int | None = None,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
):
if not root.brand_logo_default:
@@ -394,7 +396,7 @@ class AppBrandLogo(BaseObjectType):
return build_absolute_uri(root.brand_logo_default.url)
format = get_thumbnail_format(format)
- selected_size = get_thumbnail_size(size)
+ selected_size = get_thumbnail_size(size, size_rounding)
if isinstance(root, models.App):
object_type = "App"
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index d16cbe147d..e2e6b811b6 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -31,11 +31,12 @@ from ...plugins import error_codes as plugin_error_codes
from ...product import error_codes as product_error_codes
from ...shipping import error_codes as shipping_error_codes
from ...site import error_codes as site_error_codes
-from ...thumbnail import IconThumbnailFormat, ThumbnailFormat
+from ...thumbnail import IconThumbnailFormat, ThumbnailFormat, ThumbnailSizeRounding
from ...translations import error_codes as translatable_error_codes
from ...warehouse import error_codes as warehouse_error_codes
from ...webhook import error_codes as webhook_error_codes
from ..notifications import error_codes as external_notifications_error_codes
+from .descriptions import ADDED_IN_323
from .doc_category import (
DOC_CATEGORY_APPS,
DOC_CATEGORY_ATTRIBUTES,
@@ -143,6 +144,21 @@ IconThumbnailFormatEnum: Final[graphene.Enum] = to_enum(
description=IconThumbnailFormat.__doc__,
)
+
+class ThumbnailSizeRoundingEnum(graphene.Enum):
+ class Meta:
+ enum = ThumbnailSizeRounding
+ description = (
+ "Determines how a requested size is matched to an available thumbnail "
+ "size: 32, 64, 128, 256, 512, 1024, 2048, 4096.\n\n"
+ "NEAREST - the closest available size; it may be smaller than "
+ "requested.\n"
+ "UP - the smallest available size not smaller than requested, so the "
+ "image is never smaller than requested unless the original is smaller "
+ "or the requested size exceeds 4096." + ADDED_IN_323
+ )
+
+
# unit enums
MeasurementUnitsEnum: Final[graphene.Enum] = to_enum(MeasurementUnits)
DistanceUnitsEnum: Final[graphene.Enum] = to_enum(DistanceUnits)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 4067a4b25f..1495610ebb 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -5,6 +5,7 @@ import graphene
from django.core.files.storage import default_storage
from ....core.utils import build_absolute_uri
+from ....thumbnail import DEFAULT_THUMBNAIL_SIZE_ROUNDING
from ...account.enums import AddressTypeEnum
from ...core.doc_category import (
DOC_CATEGORY_APPS,
@@ -78,6 +79,7 @@ from ..enums import (
StockErrorCode,
StoredPaymentMethodRequestDeleteErrorCode,
ThumbnailFormatEnum,
+ ThumbnailSizeRoundingEnum,
TimePeriodTypeEnum,
TransactionCreateErrorCode,
TransactionEventReportErrorCode,
@@ -1071,7 +1073,17 @@ class ThumbnailField(graphene.Field):
description=(
"Desired longest side the image in pixels. Defaults to 4096. "
"Images are never cropped. "
- "Pass 0 to retrieve the original size (not recommended)."
+ "Pass 0 to retrieve the original size (not recommended). "
+ "Thumbnails are generated only in the available sizes: "
+ "32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines "
+ "which one is used."
+ ),
+ )
+ size_rounding = ThumbnailSizeRoundingEnum(
+ default_value=DEFAULT_THUMBNAIL_SIZE_ROUNDING.value,
+ description=(
+ "Determines how the requested size is matched to an available "
+ "thumbnail size." + ADDED_IN_323
),
)
format = ThumbnailFormatEnum(
@@ -1084,6 +1096,7 @@ class ThumbnailField(graphene.Field):
def __init__(self, of_type=Image, *args, **kwargs):
kwargs["size"] = self.size
+ kwargs["size_rounding"] = self.size_rounding
kwargs["format"] = self.format
super().__init__(of_type, *args, **kwargs)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index a017fba109..354ad2f6b5 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -55,6 +55,7 @@ from ...product.models import ALL_PRODUCTS_PERMISSIONS, ProductMedia, ProductMed
from ...shipping.interface import ShippingMethodData
from ...shipping.utils import convert_to_shipping_method_data
from ...tax.utils import get_display_gross_prices
+from ...thumbnail import ThumbnailSizeRounding
from ...thumbnail.utils import (
get_image_or_proxy_url,
get_thumbnail_format,
@@ -1275,6 +1276,7 @@ class OrderLine(
info,
*,
size: int = 256,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
):
variant_id = root.node.variant_id
@@ -1282,7 +1284,7 @@ class OrderLine(
return None
format = get_thumbnail_format(format)
- size = get_thumbnail_size(size)
+ size = get_thumbnail_size(size, size_rounding)
def _get_image_from_media(image):
def _resolve_url(thumbnail):
diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.py
index af56a84e0c..3533cac462 100644
--- a/saleor/graphql/product/tests/queries/test_product_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_query.py
@@ -21,7 +21,11 @@ from .....product.models import (
from .....tests.utils import dummy_editorjs
from .....thumbnail.models import Thumbnail
from .....warehouse.models import Allocation, Stock
-from ....core.enums import LanguageCodeEnum, ThumbnailFormatEnum
+from ....core.enums import (
+ LanguageCodeEnum,
+ ThumbnailFormatEnum,
+ ThumbnailSizeRoundingEnum,
+)
from ....tests.utils import get_graphql_content, get_graphql_content_from_response
QUERY_PRODUCT = """
@@ -2041,6 +2045,93 @@ def test_query_product_media_by_id_with_size_proxy_url_returned(
)
+QUERY_PRODUCT_MEDIA_BY_ID_WITH_SIZE_ROUNDING = """
+ query (
+ $productId: ID!
+ $mediaId: ID!
+ $channel: String
+ $size: Int
+ $sizeRounding: ThumbnailSizeRoundingEnum
+ ) {
+ product(id: $productId, channel: $channel) {
+ mediaById(id: $mediaId) {
+ url(size: $size, sizeRounding: $sizeRounding)
+ }
+ }
+ }
+"""
+
+
+ ("size_rounding", "expected_size"),
+ [
+ (ThumbnailSizeRoundingEnum.UP.name, 2048),
+ (ThumbnailSizeRoundingEnum.NEAREST.name, 1024),
+ ],
+)
+def test_query_product_media_by_id_with_size_rounding(
+ size_rounding, expected_size, user_api_client, product_with_image, channel_USD
+):
+ # given
+ media_id = graphene.Node.to_global_id(
+ "ProductMedia", product_with_image.media.get().pk
+ )
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", product_with_image.pk),
+ "mediaId": media_id,
+ "channel": channel_USD.slug,
+ "size": 1500,
+ "sizeRounding": size_rounding,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_PRODUCT_MEDIA_BY_ID_WITH_SIZE_ROUNDING, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert (
+ content["data"]["product"]["mediaById"]["url"]
+ == f"https://example.com/thumbnail/{media_id}/{expected_size}/"
+ )
+
+
+ ("_case", "size_rounding_variables"),
+ [
+ ("omitted", {}),
+ ("null", {"sizeRounding": None}),
+ ],
+)
+def test_query_product_media_by_id_size_rounding_defaults_to_up(
+ _case, size_rounding_variables, user_api_client, product_with_image, channel_USD
+):
+ # given
+ media_id = graphene.Node.to_global_id(
+ "ProductMedia", product_with_image.media.get().pk
+ )
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", product_with_image.pk),
+ "mediaId": media_id,
+ "channel": channel_USD.slug,
+ "size": 1500,
+ **size_rounding_variables,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_PRODUCT_MEDIA_BY_ID_WITH_SIZE_ROUNDING, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert (
+ content["data"]["product"]["mediaById"]["url"]
+ == f"https://example.com/thumbnail/{media_id}/2048/"
+ )
+
+
def test_query_product_media_by_id_with_size_thumbnail_url_returned(
user_api_client, product_with_image, channel_USD
):
diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.py
index 39660dde98..d59589abc6 100644
--- a/saleor/graphql/product/types/categories.py
+++ b/saleor/graphql/product/types/categories.py
@@ -6,6 +6,7 @@ from ....core.search import prefix_search
from ....permission.utils import has_one_of_permissions
from ....product import models
from ....product.models import ALL_PRODUCTS_PERMISSIONS
+from ....thumbnail import ThumbnailSizeRounding
from ....thumbnail.utils import (
get_image_or_proxy_url,
get_thumbnail_format,
@@ -126,6 +127,7 @@ class Category(ModelObjectType[models.Category]):
root: models.Category,
info,
size: int | None = None,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
) -> None | Image | Promise[Image]:
if not root.background_image:
@@ -136,7 +138,7 @@ class Category(ModelObjectType[models.Category]):
return Image(url=root.background_image.url, alt=alt)
format = get_thumbnail_format(format)
- selected_size = get_thumbnail_size(size)
+ selected_size = get_thumbnail_size(size, size_rounding)
def _resolve_background_image(thumbnail):
url = get_image_or_proxy_url(
diff --git a/saleor/graphql/product/types/collections.py b/saleor/graphql/product/types/collections.py
index 334530d27d..f85b4d3864 100644
--- a/saleor/graphql/product/types/collections.py
+++ b/saleor/graphql/product/types/collections.py
@@ -7,6 +7,7 @@ from promise import Promise
from ....core.search import prefix_search
from ....permission.enums import ProductPermissions
from ....product import models
+from ....thumbnail import ThumbnailSizeRounding
from ....thumbnail.utils import (
get_image_or_proxy_url,
get_thumbnail_format,
@@ -118,6 +119,7 @@ class Collection(ChannelContextType[models.Collection]):
root: ChannelContext[models.Collection],
info: ResolveInfo,
size: int | None = None,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
) -> None | Image | Promise[Image]:
node = root.node
@@ -129,7 +131,7 @@ class Collection(ChannelContextType[models.Collection]):
return Image(url=node.background_image.url, alt=alt)
format = get_thumbnail_format(format)
- selected_size = get_thumbnail_size(size)
+ selected_size = get_thumbnail_size(size, size_rounding)
def _resolve_background_image(thumbnail):
url = get_image_or_proxy_url(
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 72a8fba117..f0f92d136f 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -29,6 +29,7 @@ from ....tax.utils import (
get_tax_calculation_strategy,
get_tax_rate_for_country,
)
+from ....thumbnail import ThumbnailSizeRounding
from ....thumbnail.utils import (
get_image_or_proxy_url,
get_original_image_proxy_url,
@@ -1127,10 +1128,11 @@ class Product(ChannelContextType[models.Product]):
info,
*,
size: int = 256,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
):
format = get_thumbnail_format(format)
- size = get_thumbnail_size(size)
+ size = get_thumbnail_size(size, size_rounding)
def return_first_thumbnail(product_media):
if not product_media:
@@ -1986,6 +1988,7 @@ class ProductMedia(ModelObjectType[models.ProductMedia]):
info,
*,
size: int | None = None,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
) -> str | None | Promise[str]:
if root.external_url and root.type != ProductMediaTypes.IMAGE:
@@ -2005,7 +2008,7 @@ class ProductMedia(ModelObjectType[models.ProductMedia]):
# Else, return proxy URL for thumbnail.
format = get_thumbnail_format(format)
- selected_size = get_thumbnail_size(size)
+ selected_size = get_thumbnail_size(size, size_rounding)
def _resolve_url(thumbnail) -> str:
url = get_image_or_proxy_url(
@@ -2062,6 +2065,7 @@ class ProductImage(BaseObjectType):
info,
*,
size: int | None = None,
+ size_rounding: ThumbnailSizeRounding | None = None,
format: str | None = None,
) -> None | str | Promise[str]:
if not root.image:
@@ -2071,7 +2075,7 @@ class ProductImage(BaseObjectType):
return build_absolute_uri(root.image.url)
format = get_thumbnail_format(format)
- selected_size = get_thumbnail_size(size)
+ selected_size = get_thumbnail_size(size, size_rounding)
def _resolve_url(thumbnail):
url = get_image_or_proxy_url(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index f03c997a04..494d91fb13 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3528,10 +3528,17 @@ type User implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(categ
"""The avatar of the user."""
avatar(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
@@ -4132,10 +4139,17 @@ type Product implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(ca
"""Thumbnail of the product."""
thumbnail(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
@@ -4444,10 +4458,17 @@ type Category implements Node & ObjectWithMetadata @doc(category: "Products") {
"""Background image of the category."""
backgroundImage(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
@@ -4903,6 +4924,19 @@ type Image {
alt: String
}
+"""
+Determines how a requested size is matched to an available thumbnail size: 32, 64, 128, 256, 512, 1024, 2048, 4096.
+
+NEAREST - the closest available size; it may be smaller than requested.
+UP - the smallest available size not smaller than requested, so the image is never smaller than requested unless the original is smaller or the requested size exceeds 4096.
+
+Added in Saleor 3.23.
+"""
+enum ThumbnailSizeRoundingEnum {
+ NEAREST
+ UP
+}
+
enum ThumbnailFormatEnum {
ORIGINAL
AVIF
@@ -9763,10 +9797,17 @@ type ProductImage @doc(category: "Products") {
"""The URL of the image."""
url(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
@@ -9838,10 +9879,17 @@ type ProductMedia implements Node & ObjectWithMetadata @doc(category: "Products"
"""The URL of the media."""
url(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
@@ -10279,10 +10327,17 @@ type Collection implements Node & ObjectWithMetadata @doc(category: "Products")
"""Background image of the collection."""
backgroundImage(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
@@ -12455,10 +12510,17 @@ type OrderLine implements Node & ObjectWithMetadata @doc(category: "Orders") {
taxRate: Float!
thumbnail(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
@@ -14335,10 +14397,17 @@ type AppBrandLogo @doc(category: "Apps") {
"""URL to the default logo image."""
default(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
@@ -33286,10 +33355,17 @@ type AppManifestBrandLogo @doc(category: "Apps") {
"""Data URL with a base64 encoded logo image."""
default(
"""
- Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended).
+ Desired longest side the image in pixels. Defaults to 4096. Images are never cropped. Pass 0 to retrieve the original size (not recommended). Thumbnails are generated only in the available sizes: 32, 64, 128, 256, 512, 1024, 2048, 4096; `sizeRounding` determines which one is used.
"""
size: Int
+ """
+ Determines how the requested size is matched to an available thumbnail size.
+
+ Added in Saleor 3.23.
+ """
+ sizeRounding: ThumbnailSizeRoundingEnum = UP
+
"""
The format of the image. When not provided, format of the original image will be used.
"""
diff --git a/saleor/thumbnail/__init__.py b/saleor/thumbnail/__init__.py
index 09252d4406..dbdb85e94f 100644
--- a/saleor/thumbnail/__init__.py
+++ b/saleor/thumbnail/__init__.py
@@ -1,3 +1,5 @@
+from enum import Enum
+
# defines the available thumbnail resolutions
THUMBNAIL_SIZES = [32, 64, 128, 256, 512, 1024, 2048, 4096]
@@ -18,6 +20,19 @@ class ThumbnailFormat:
]
+class ThumbnailSizeRounding(str, Enum):
+ """Determine how a requested size is matched to an available thumbnail size.
+
+ NEAREST - use the closest available size; it may be smaller than requested.
+ UP - use the smallest available size that is not smaller than requested.
+ """
+
+ NEAREST = "NEAREST"
+ UP = "UP"
+
+
+DEFAULT_THUMBNAIL_SIZE_ROUNDING = ThumbnailSizeRounding.UP
+
ALLOWED_THUMBNAIL_FORMATS = {ThumbnailFormat.AVIF, ThumbnailFormat.WEBP}
# PIL-supported file formats as found here:
diff --git a/saleor/thumbnail/tests/test_utils.py b/saleor/thumbnail/tests/test_utils.py
index 94905d50d7..5062923e8f 100644
--- a/saleor/thumbnail/tests/test_utils.py
+++ b/saleor/thumbnail/tests/test_utils.py
@@ -6,7 +6,7 @@ import pytest
from django.core.files import File
from PIL.JpegImagePlugin import JpegImageFile
-from .. import FILE_NAME_MAX_LENGTH, ThumbnailFormat
+from .. import FILE_NAME_MAX_LENGTH, ThumbnailFormat, ThumbnailSizeRounding
from ..models import Thumbnail
from ..utils import (
ProcessedImage,
@@ -20,16 +20,56 @@ from ..utils import (
@pytest.mark.parametrize(
("size", "expected_value"),
- [(1, 32), (16, 32), (60, 64), (80, 64), (256, 256), (8000, 4096), (15000, 4096)],
+ [
+ (None, 4096),
+ (1, 32),
+ (32, 32),
+ (33, 64),
+ (60, 64),
+ (1024, 1024),
+ (1025, 2048),
+ (1500, 2048),
+ (8000, 4096),
+ ],
+)
+def test_get_thumbnail_size_with_up_rounding(size, expected_value):
+ # when
+ returned_size = get_thumbnail_size(size, ThumbnailSizeRounding.UP)
+
+ # then
+ assert returned_size == expected_value
+
+
+ ("size", "expected_value"),
+ [
+ (None, 4096),
+ (1, 32),
+ (48, 32),
+ (49, 64),
+ (80, 64),
+ (768, 512),
+ (769, 1024),
+ (1500, 1024),
+ (8000, 4096),
+ ],
)
-def test_get_thumbnail_size(size, expected_value):
+def test_get_thumbnail_size_with_nearest_rounding(size, expected_value):
# when
- returned_size = get_thumbnail_size(size)
+ returned_size = get_thumbnail_size(size, ThumbnailSizeRounding.NEAREST)
# then
assert returned_size == expected_value
+def test_get_thumbnail_size_defaults_to_up_rounding():
+ # when
+ returned_size = get_thumbnail_size(1500)
+
+ # then
+ assert returned_size == 2048
+
+
@pytest.mark.parametrize(
("file_name", "size", "format", "expected_name"),
[
diff --git a/saleor/thumbnail/utils.py b/saleor/thumbnail/utils.py
index d0954dcba4..2fe0520a6f 100644
--- a/saleor/thumbnail/utils.py
+++ b/saleor/thumbnail/utils.py
@@ -16,11 +16,13 @@ from PIL import Image
from ..product import ProductMediaTypes
from . import (
DEFAULT_THUMBNAIL_SIZE,
+ DEFAULT_THUMBNAIL_SIZE_ROUNDING,
FILE_NAME_MAX_LENGTH,
MIME_TYPE_TO_PIL_IDENTIFIER,
THUMBNAIL_SIZES,
IconThumbnailFormat,
ThumbnailFormat,
+ ThumbnailSizeRounding,
)
from .exceptions import ImageTooLargeError
@@ -65,8 +67,16 @@ def get_original_image_proxy_url(
return reverse("original-image", kwargs=kwargs)
-def get_thumbnail_size(size: int | None) -> int:
- """Return the closest size to the given one of the available sizes."""
+def get_thumbnail_size(
+ size: int | None, rounding: ThumbnailSizeRounding | None = None
+) -> int:
+ """Return the available size matching the given one.
+
+ With `NEAREST` rounding the closest available size is returned, with `UP`
+ rounding the smallest available size not smaller than the given one. Sizes
+ above the largest available size resolve to the largest one. When `rounding`
+ is not given, `DEFAULT_THUMBNAIL_SIZE_ROUNDING` is used.
+ """
if size is None:
requested_size = DEFAULT_THUMBNAIL_SIZE
else:
@@ -74,6 +84,10 @@ def get_thumbnail_size(size: int | None) -> int:
if requested_size in THUMBNAIL_SIZES:
return requested_size
+ if (rounding or DEFAULT_THUMBNAIL_SIZE_ROUNDING) == ThumbnailSizeRounding.UP:
+ return next(
+ (s for s in THUMBNAIL_SIZES if s >= requested_size), THUMBNAIL_SIZES[-1]
+ )
return min(THUMBNAIL_SIZES, key=lambda x: abs(x - requested_size))