Processing HDR images with Rails

Stack:

  • Dropzone
  • Rails 7.0.8
  • Imagemagick

Add .hdr to the acceptedFiles collection when instantiating Dropzone:

  let dropzone = new Dropzone(controller.element, {
    ...
    acceptedFiles: "image/png, image/jpg, image/jpeg, image/webp, .hdr",

  });

Crank the max file size way up…

let dropzone = new Dropzone(controller.element, {
    ...
    maxFilesize: 750,

  });

In rails set up active_storage.rb under initializers and put the following in it:

# frozen_string_literal: true

module Web
  class Application < Rails::Application
    config.active_storage.variant_processor = :mini_magick
    config.active_storage.variable_content_types += ["application/envi.hdr"] # from https://github.com/rails/marcel/blob/main/data/tika.xml
  end
end

Note that I change the image processor from vips to mini_magick. While libvips does list HDR as a supported file type, I found mini_magick more reliable. I could also test the results via the command line:

magick input.hdr -resize 10% output.jpg

config.active_storage.variable_content_types += ["application/envi.hdr"] is the key to getting rails to recognize .hrd as a file type. Otherwise you end up with ActiveStorage::InvariableError (ActiveStorage::InvariableError).

In my model I then altered the way I handled variants to (based on the guidance from Drifting Ruby):

  has_one_attached :file do |blob|
    blob.variant :thumb, resize_to_limit: [300, 300], convert: :jpeg
  end

I’m then able to refer to the generated thumbnail in the my views:

<%= image_tag backdrop.file.variant(:thumb),  class: "h-auto max-w-full rounded-lg" %>

Do not talk to ChatGPT or Gemini because you’ll end up with something like:

Leave a comment