Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Preprocess product images in background job to create their variations (#13352)
Damian Legawiecb9b5e3dbb2e7
diff --git a/admin/app/views/spree/admin/shared/_product_image.html.erb b/admin/app/views/spree/admin/shared/_product_image.html.erbindex a4631e1a59..f7fadee154 100644--- a/admin/app/views/spree/admin/shared/_product_image.html.erb+++ b/admin/app/views/spree/admin/shared/_product_image.html.erb@@ -1,11 +1,12 @@<% width ||= 50 %><% height ||= 50 %>+<% variant ||= :mini %><% image ||= object.default_image %><% if image.present? && image.attached? && image.variable? %><% alt ||= image.alt || object.name %><div class="admin-product-image-container">- <%= spree_image_tag(image, width: width, height: height, alt: alt) %>+ <%= spree_image_tag(image, variant: variant, alt: alt, width: width, height: height) %></div><% else %><%= render 'spree/admin/shared/no_image', width: width, height: height %>diff --git a/core/app/helpers/spree/images_helper.rb b/core/app/helpers/spree/images_helper.rbindex 82e4cdefe5..a67343b2f9 100644--- a/core/app/helpers/spree/images_helper.rb+++ b/core/app/helpers/spree/images_helper.rb@@ -7,10 +7,17 @@ module Spree# @param options [Hash] options for the image tag# @option options [Integer] :width the width of the image# @option options [Integer] :height the height of the image+ # @option options [Symbol] :variant use a preprocessed named variant (e.g., :mini, :small, :medium, :large, :xlarge)def spree_image_tag(image, options = {})+ url_options = if options[:variant].present?+ { variant: options[:variant] }+ else+ { width: options[:width], height: options[:height], format: options[:format] }+ end+image_tag(- spree_image_url(image, { width: options[:width], height: options[:height], format: options[:format] }),- options+ spree_image_url(image, url_options),+ options.except(:variant, :format))end@@ -19,9 +26,17 @@ module Spreereturn unless image.variable?return if image.respond_to?(:attached?) && !image.attached?url_helpers = respond_to?(:main_app) ? main_app : Rails.application.routes.url_helpers++ # Use preprocessed named variant if specified (e.g., :mini, :small, :medium, :large, :xlarge)+ if options[:variant].present?+ return url_helpers.cdn_image_url(image.variant(options[:variant]))+ end++ # Dynamic variant generation for width/height optionswidth = options[:width]height = options[:height]+ # Double dimensions for retina displayswidth *= 2 if width.present?height *= 2 if height.present?@@ -74,27 +89,28 @@ module Spree# @param options [Hash] options for the image variant# @option options [Integer] :width the width of the image# @option options [Integer] :height the height of the image+ #+ # @note The key order matters for variation digest matching with preprocessed variants.+ # Active Storage reorders keys alphabetically, so use: format, resize_to_fill/limit, saver+ # @note Use string values (not symbols) for format because variation keys are JSON-encoded+ # in URLs and JSON converts symbols to strings, causing digest mismatches.def spree_image_variant_options(options = {})- {- saver: options[:format] == :png ? png_variant_options : webp_variant_options,- format: options[:format] || :webp- }.merge(options.except(:format))+ format_opt = options[:format]&.to_s+ saver_options = format_opt == "png" ? png_saver_options : Spree::Asset::WEBP_SAVER_OPTIONS+ format = format_opt || "webp"++ # Build hash in alphabetical order to match Active Storage's key ordering+ result = {}+ result[:format] = format+ result[:resize_to_fill] = options[:resize_to_fill] if options[:resize_to_fill]+ result[:resize_to_limit] = options[:resize_to_limit] if options[:resize_to_limit]+ result[:saver] = saver_options+ resultendprivate- def webp_variant_options- {- strip: true,- quality: 75,- lossless: false,- alpha_q: 85,- reduction_effort: 6,- smart_subsample: true- }- end-- def png_variant_options+ def png_saver_options{strip: true,compression_level: 8,diff --git a/core/app/models/spree/asset.rb b/core/app/models/spree/asset.rbindex c8545c7e07..5bb987ad37 100644--- a/core/app/models/spree/asset.rb+++ b/core/app/models/spree/asset.rb@@ -12,9 +12,33 @@ module Spreebelongs_to :viewable, polymorphic: true, touch: trueacts_as_list scope: [:viewable_id, :viewable_type]- delegate :key, :attached?, :variant, :variable?, :blob, :filename, to: :attachment+ delegate :key, :attached?, :variant, :variable?, :blob, :filename, :variation, to: :attachment- has_one_attached :attachment, service: Spree.public_storage_service_name+ WEBP_SAVER_OPTIONS = {+ strip: true,+ quality: 75,+ lossless: false,+ alpha_q: 85,+ reduction_effort: 6,+ smart_subsample: true+ }.freeze++ has_one_attached :attachment, service: Spree.public_storage_service_name do |attachable|+ # Note: Key order matters for variation digest matching.+ # Active Storage reorders keys alphabetically when calling variant(:name),+ # so we must define them in alphabetical order: format, resize_to_fill, saver+ #+ # IMPORTANT: Use string values (not symbols) for format because the variation key+ # is JSON-encoded in URLs. JSON converts symbols to strings, so "webp" != :webp+ # after round-tripping, which causes digest mismatches.+ Spree::Config.product_image_variant_sizes.each do |name, (width, height)|+ attachable.variant name,+ format: "webp",+ resize_to_fill: [width, height],+ saver: WEBP_SAVER_OPTIONS,+ preprocessed: true+ end+ enddefault_scope { includes(attachment_attachment: :blob) }diff --git a/core/app/models/spree/image.rb b/core/app/models/spree/image.rbindex a7749a57b4..11565c2372 100644--- a/core/app/models/spree/image.rb+++ b/core/app/models/spree/image.rb@@ -51,7 +51,8 @@ module Spreeenddef plp_url- generate_url(size: self.class.styles[:plp_and_carousel])+ Spree::Deprecation.warn "Image#plp_url is deprecated. Use variant(:large) instead."+ generate_url(size: self.class.styles[:large])endprivatediff --git a/core/app/models/spree/image/configuration/active_storage.rb b/core/app/models/spree/image/configuration/active_storage.rbindex 963cefead6..59bd0acbd0 100644--- a/core/app/models/spree/image/configuration/active_storage.rb+++ b/core/app/models/spree/image/configuration/active_storage.rb@@ -7,25 +7,16 @@ module Spreeincluded dovalidates :attachment, attached: true, content_type: Rails.application.config.active_storage.web_image_content_types+ # Returns image styles derived from Spree::Config.product_image_variant_sizes+ # Format: { variant_name: 'WxH>' } for API compatibilitydef self.styles- @styles ||= {- mini: '48x48>',- small: '100x100>',- product: '240x240>',- pdp_thumbnail: '160x200>',- plp_and_carousel: '448x600>',- plp_and_carousel_xs: '254x340>',- plp_and_carousel_sm: '350x468>',- plp_and_carousel_md: '222x297>',- plp_and_carousel_lg: '278x371>',- large: '600x600>',- plp: '278x371>',- zoomed: '650x870>'- }+ @styles ||= Spree::Config.product_image_variant_sizes.transform_values do |dimensions|+ "#{dimensions[0]}x#{dimensions[1]}>"+ endenddef default_style- :product+ :smallendendenddiff --git a/core/app/models/spree/themes/default.rb b/core/app/models/spree/themes/default.rbindex 830fde23ab..2dffcdb616 100644--- a/core/app/models/spree/themes/default.rb+++ b/core/app/models/spree/themes/default.rb@@ -85,10 +85,13 @@ module Spreepreference :border_shadow_blur, :integer, default: 5# PRODUCT IMAGES- preference :product_listing_image_height, :integer, default: 300- preference :product_listing_image_width, :integer, default: 300- preference :product_listing_image_height_mobile, :integer, default: 190- preference :product_listing_image_width_mobile, :integer, default: 190+ # These defaults match preprocessed variant sizes for optimal performance:+ # Desktop (360x360) → large variant (720x720 at 2x)+ # Mobile (200x200) → medium variant (400x400 at 2x)+ preference :product_listing_image_height, :integer, default: 360+ preference :product_listing_image_width, :integer, default: 360+ preference :product_listing_image_height_mobile, :integer, default: 200+ preference :product_listing_image_width_mobile, :integer, default: 200endendenddiff --git a/core/lib/spree/core/configuration.rb b/core/lib/spree/core/configuration.rbindex c010c467f1..2344fef112 100644--- a/core/lib/spree/core/configuration.rb+++ b/core/lib/spree/core/configuration.rb@@ -46,6 +46,36 @@ module Spreepreference :expedited_exchanges_days_window, :integer, default: 14 # the amount of days the customer has to return their item after the expedited exchange is shipped in order to avoid being chargedpreference :geocode_addresses, :boolean, default: truepreference :images_save_from_url_job_attempts, :integer, default: 5++ # Preprocessed product image variant sizes at 2x retina resolution.+ # These variants are generated on upload to reduce runtime processing.+ # When using spree_image_tag, pass half these values (e.g., width: 64 for mini).+ #+ # Default sizes:+ # mini (128x128) - admin thumbnails, checkout line items+ # small (256x256) - cart/order items, gallery thumbnails+ # medium (400x400) - mobile listing, admin media+ # large (720x720) - product listing, mobile gallery+ # xlarge (2000x2000) - gallery main, lightbox+ #+ # To customize, override in your initializer:+ # Spree::Config.product_image_variant_sizes = {+ # mini: [128, 128],+ # small: [256, 256],+ # # ... your custom sizes+ # }+ attr_writer :product_image_variant_sizes++ def product_image_variant_sizes+ @product_image_variant_sizes ||= {+ mini: [128, 128],+ small: [256, 256],+ medium: [400, 400],+ large: [720, 720],+ xlarge: [2000, 2000],+ og_image: [1200, 630]+ }+ endpreference :layout, :string, deprecated: 'Please use Spree::Frontend::Config[:layout] instead'preference :logo, :string, deprecated: truepreference :mailer_logo, :string, deprecated: truediff --git a/core/spec/helpers/images_helper_spec.rb b/core/spec/helpers/images_helper_spec.rbindex e54c4dcb1a..b0e297473c 100644--- a/core/spec/helpers/images_helper_spec.rb+++ b/core/spec/helpers/images_helper_spec.rb@@ -20,6 +20,20 @@ describe Spree::ImagesHelper, type: :helper doexpect(helper).to receive(:image_tag).with('image_url', { width: 100, height: 100 }).and_return('image_tag')expect(helper.spree_image_tag(image, width: 100, height: 100)).to eq('image_tag')end++ context 'when variant option is provided' do+ it 'passes only variant to spree_image_url and excludes it from image_tag options' do+ expect(helper).to receive(:spree_image_url).with(image, { variant: :mini }).and_return('image_url')+ expect(helper).to receive(:image_tag).with('image_url', { class: 'test-class' }).and_return('image_tag')+ expect(helper.spree_image_tag(image, variant: :mini, class: 'test-class')).to eq('image_tag')+ end++ it 'ignores width, height, and format when variant is provided' do+ expect(helper).to receive(:spree_image_url).with(image, { variant: :small }).and_return('image_url')+ expect(helper).to receive(:image_tag).with('image_url', { width: 100, height: 100 }).and_return('image_tag')+ expect(helper.spree_image_tag(image, variant: :small, width: 100, height: 100, format: :png)).to eq('image_tag')+ end+ endenddescribe '#spree_image_url' do@@ -68,11 +82,27 @@ describe Spree::ImagesHelper, type: :helper docontext 'when format is provided' doit 'returns a url with the correct format' dovariant = double('variant')- expect(image).to receive(:variant).with(hash_including(resize_to_fill: [200, 200], format: :png)).and_return(variant)+ expect(image).to receive(:variant).with(hash_including(resize_to_fill: [200, 200], format: "png")).and_return(variant)expect(Rails.application.routes.url_helpers).to receive(:cdn_image_url).and_return('cdn_url')expect(helper.spree_image_url(image, width: 100, height: 100, format: :png)).to eq('cdn_url')endend++ context 'when variant option is provided' do+ it 'uses the named variant directly' do+ variant = double('variant')+ expect(image).to receive(:variant).with(:mini).and_return(variant)+ expect(Rails.application.routes.url_helpers).to receive(:cdn_image_url).and_return('cdn_url')+ expect(helper.spree_image_url(image, variant: :mini)).to eq('cdn_url')+ end++ it 'ignores width and height when variant is provided' do+ variant = double('variant')+ expect(image).to receive(:variant).with(:small).and_return(variant)+ expect(Rails.application.routes.url_helpers).to receive(:cdn_image_url).and_return('cdn_url')+ expect(helper.spree_image_url(image, variant: :small, width: 100, height: 100)).to eq('cdn_url')+ end+ endenddescribe '#spree_asset_aspect_ratio' dodiff --git a/core/spec/models/spree/asset_spec.rb b/core/spec/models/spree/asset_spec.rbindex 7bc0140497..bed7965f34 100644--- a/core/spec/models/spree/asset_spec.rb+++ b/core/spec/models/spree/asset_spec.rb@@ -3,6 +3,25 @@ require 'spec_helper'describe Spree::Asset, type: :model doit_behaves_like 'metadata'+ describe 'named variants' do+ let(:reflection) { described_class.attachment_reflections['attachment'] }++ it 'defines preprocessed variants based on config' do+ expected_variants = Spree::Config.product_image_variant_sizes.keys+ expect(reflection.named_variants.keys).to match_array(expected_variants)+ end++ Spree::Config.product_image_variant_sizes.each do |name, (width, height)|+ it "defines :#{name} variant with correct options" do+ named_variant = reflection.named_variants[name]+ expect(named_variant).to be_present+ expect(named_variant.transformations[:resize_to_fill]).to eq([width, height])+ expect(named_variant.transformations[:format]).to eq("webp")+ expect(named_variant.instance_variable_get(:@preprocessed)).to eq(true)+ end+ end+ end+describe '#product' doit 'returns the product for the asset' dovariant = create(:variant)diff --git a/storefront/app/views/spree/checkout/_line_item.html.erb b/storefront/app/views/spree/checkout/_line_item.html.erbindex 687dfed31f..87177ff79e 100644--- a/storefront/app/views/spree/checkout/_line_item.html.erb+++ b/storefront/app/views/spree/checkout/_line_item.html.erb@@ -5,7 +5,7 @@</span><% image = line_item.variant.default_image %><% if image.present? && image.attached? && image.variable? %>- <%= spree_image_tag(image, class: 'rounded-sm border border-default bg-transparent object-cover object-center', loading: :lazy, width: 64, height: 64) %>+ <%= spree_image_tag(image, class: 'rounded-sm border border-default bg-transparent object-cover object-center', loading: :lazy, variant: :mini, width: 64, height: 64) %><% else %><div class="w-16 h-16 bg-accent border border-default rounded-sm"></div><% end %>diff --git a/storefront/app/views/themes/default/spree/orders/_line_item.html.erb b/storefront/app/views/themes/default/spree/orders/_line_item.html.erbindex 9c6be01d5d..5f71506f96 100644--- a/storefront/app/views/themes/default/spree/orders/_line_item.html.erb+++ b/storefront/app/views/themes/default/spree/orders/_line_item.html.erb@@ -5,7 +5,7 @@<% image = line_item.variant.default_image %><% if image.present? && image.attached? && image.variable? %><%= link_to spree_storefront_resource_url(line_item.product), data: { 'turbo-frame': '_top' } do %>- <%= spree_image_tag(image, width: 128, height: 128, class: 'object-cover', loading: :lazy) %>+ <%= spree_image_tag(image, width: 128, height: 128, variant: :small, class: 'object-cover', loading: :lazy) %><% end %><% else %><div class="w-32 h-32 bg-accent"></div>diff --git a/storefront/app/views/themes/default/spree/products/_featured_image.html.erb b/storefront/app/views/themes/default/spree/products/_featured_image.html.erbindex 1759714143..f624fa37da 100644--- a/storefront/app/views/themes/default/spree/products/_featured_image.html.erb+++ b/storefront/app/views/themes/default/spree/products/_featured_image.html.erb@@ -12,10 +12,10 @@<% image_hover_class = object.secondary_image.present? && object.secondary_image.attached? ?"w-full group-hover:opacity-0 transition-opacity duration-500 z-10 relative h-full bg-background product-card !max-h-full #{object_class}" :"w-full h-full !max-h-full #{object_class}" %>- <%= spree_image_tag(object.default_image, width: width, height: height, loading: :lazy, alt: "#{object.name} #{Spree.t('storefront.products.primary_image', default: 'primary image')}", class: image_hover_class) %>+ <%= spree_image_tag(object.default_image, width: width, height: height, variant: :medium, loading: :lazy, alt: "#{object.name} #{Spree.t('storefront.products.primary_image', default: 'primary image')}", class: image_hover_class) %><% if object.secondary_image.present? && object.secondary_image.attached? %><% secondary_image_class = "w-full absolute top-0 left-0 opacity-100 h-full !max-h-full #{object_class}" %>- <%= spree_image_tag(object.secondary_image, width: width, height: height, loading: :lazy, alt: "#{object.name} #{Spree.t('storefront.products.secondary_image', default: 'secondary image')}", class: secondary_image_class) %>+ <%= spree_image_tag(object.secondary_image, width: width, height: height, variant: :medium, loading: :lazy, alt: "#{object.name} #{Spree.t('storefront.products.secondary_image', default: 'secondary image')}", class: secondary_image_class) %><% end %></figure><% else %>diff --git a/storefront/app/views/themes/default/spree/products/_json_ld.html.erb b/storefront/app/views/themes/default/spree/products/_json_ld.html.erbindex ecbce25779..3dadec1ea7 100644--- a/storefront/app/views/themes/default/spree/products/_json_ld.html.erb+++ b/storefront/app/views/themes/default/spree/products/_json_ld.html.erb@@ -7,7 +7,7 @@"url": <%= spree.product_url(product, host: current_store.url_or_custom_domain).to_json.html_safe %>,<% if product.featured_image %>"image": [- <%= spree_image_url(product.featured_image, width: 630, height: 630).to_json.html_safe %>+ <%= spree_image_url(product.featured_image, variant: :large).to_json.html_safe %>],<% end %><% if product.description.present? %>diff --git a/storefront/app/views/themes/default/spree/products/_media_gallery.html.erb b/storefront/app/views/themes/default/spree/products/_media_gallery.html.erbindex a408eba382..9d6c63661f 100644--- a/storefront/app/views/themes/default/spree/products/_media_gallery.html.erb+++ b/storefront/app/views/themes/default/spree/products/_media_gallery.html.erb@@ -21,7 +21,7 @@class="relative aspect-1 w-full block "id="thumb-desktop-product-image-<%= image.id %>"data-turbo-permanent>- <%= spree_image_tag(image, width: 100, height: 100, alt: image_alt(image), class: 'w-full h-full') %>+ <%= spree_image_tag(image, variant: :small, alt: image_alt(image), class: 'w-full h-full') %></div></div><% end %>@@ -39,11 +39,11 @@class="product-image relative w-full aspect-1"id="main-desktop-product-image-<%= image.id %>"data-turbo-permanent>- <%= link_to spree_image_url(image, width: 1000, height: 1000), data: { pswp_width: "2000", pswp_height: "2000" } do %>+ <%= link_to spree_image_url(image, variant: :xlarge), data: { pswp_width: "2000", pswp_height: "2000" } do %><div class="zoom-icon hidden absolute bottom-2 right-2 p-4 bg-background rounded-full opacity-75 hover:opacity-100"><%= render 'spree/shared/icons/zoom' %></div>- <%= spree_image_tag(image, width: 1000, height: 1000, alt: image_alt(image), class: 'w-full h-full') %>+ <%= spree_image_tag(image, variant: :xlarge, alt: image_alt(image), class: 'w-full h-full') %><% end %></div></div>@@ -70,11 +70,11 @@<div class="swiper-wrapper"><% images.each do |image| %><div class="swiper-slide aspect-1" id="swiper-slide-<%= image.id %>">- <%= link_to spree_image_url(image, width: 2000, height: 2000), class: "absolute top-2 right-2 p-2 bg-background rounded-full opacity-75 hover:opacity-100", data: { pswp_width: "2000", pswp_height: "2000" } do %>+ <%= link_to spree_image_url(image, variant: :xlarge), class: "absolute top-2 right-2 p-2 bg-background rounded-full opacity-75 hover:opacity-100", data: { pswp_width: "2000", pswp_height: "2000" } do %><%= render 'spree/shared/icons/zoom' %><% end %><%= render 'spree/products/label', product: product, mobile_pdp: true %>- <%= spree_image_tag(image, width: 360, height: 360, alt: image_alt(image), class: 'h-full w-full object-cover object-center', style: 'min-height: 358px') %>+ <%= spree_image_tag(image, variant: :large, alt: image_alt(image), class: 'h-full w-full object-cover object-center', style: 'min-height: 358px') %></div><% end %></div>diff --git a/storefront/app/views/themes/default/spree/shared/_meta_tags.html.erb b/storefront/app/views/themes/default/spree/shared/_meta_tags.html.erbindex 7bd2b576a2..6031a4fd32 100644--- a/storefront/app/views/themes/default/spree/shared/_meta_tags.html.erb+++ b/storefront/app/views/themes/default/spree/shared/_meta_tags.html.erb@@ -22,7 +22,11 @@<meta property="og:description" content="<%= h(og_description) %>"><% if page_image.present? && page_image.attached? && page_image.variable? %>- <% image_url = spree_image_url(page_image, width: 1200, height: 630) %>+ <% if @product %>+ <% image_url = spree_image_url(page_image, variant: :og_image) %>+ <% else %>+ <% image_url = spree_image_url(page_image, width: 1200, height: 630) %>+ <% end %><meta property="og:image" content="<%= image_url %>"><meta property="og:image:secure_url" content="<%= image_url %>">diff --git a/storefront/app/views/themes/default/spree/shared/_order_line_item.html.erb b/storefront/app/views/themes/default/spree/shared/_order_line_item.html.erbindex 954dc7159f..e8dc44d564 100644--- a/storefront/app/views/themes/default/spree/shared/_order_line_item.html.erb+++ b/storefront/app/views/themes/default/spree/shared/_order_line_item.html.erb@@ -6,7 +6,7 @@<% image = line_item.variant.default_image %><% if image.present? && image.attached? && image.variable? %><%= link_to spree_storefront_resource_url(line_item.product, relative: true) do %>- <%= spree_image_tag(image, width: 128, height: 128, loading: :lazy) %>+ <%= spree_image_tag(image, width: 128, height: 128, variant: :small, loading: :lazy) %><% end %><% else %><div class="w-32 h-32 bg-accent"></div>diff --git a/storefront/lib/generators/spree/storefront/theme/templates/model.rb.tt b/storefront/lib/generators/spree/storefront/theme/templates/model.rb.ttindex 714c0b31eb..48bb0af503 100644--- a/storefront/lib/generators/spree/storefront/theme/templates/model.rb.tt+++ b/storefront/lib/generators/spree/storefront/theme/templates/model.rb.tt@@ -84,10 +84,13 @@ module Spreepreference :border_shadow_blur, :integer, default: 5# PRODUCT IMAGES- preference :product_listing_image_height, :integer, default: 300- preference :product_listing_image_width, :integer, default: 300- preference :product_listing_image_height_mobile, :integer, default: 190- preference :product_listing_image_width_mobile, :integer, default: 190+ # These defaults match preprocessed variant sizes for optimal performance:+ # Desktop (360x360) → large variant (720x720 at 2x)+ # Mobile (200x200) → medium variant (400x400 at 2x)+ preference :product_listing_image_height, :integer, default: 360+ preference :product_listing_image_width, :integer, default: 360+ preference :product_listing_image_height_mobile, :integer, default: 200+ preference :product_listing_image_width_mobile, :integer, default: 200# Returns an array of available layout section classes for the theme, eg. header, footer, newsletter, etc.#