34
loading...
This website collects cookies to deliver better user experience
# app/previewers/heic_previewer.rb
class HeicPreviewer < ActiveStorage::Previewer
CONTENT_TYPE = "image/heic"
class << self
def accept?(blob)
blob.content_type == CONTENT_TYPE && minimagick_exists?
end
def minimagick_exists?
return @minimagick_exists unless @minimagick_exists.blank?
@minimagick_exists = defined?(ImageProcessing::MiniMagick)
Rails.logger.error "#{self.class} :: MiniMagick is not installed" unless @minimagick_exists
@minimagick_exists
end
end
def preview(transformations)
download_blob_to_tempfile do |input|
io = ImageProcessing::MiniMagick.source(input).convert("png").call
yield io: io, filename: "#{blob.filename.base}.png", content_type: "image/png"
end
end
end
# config/initializers/active_storage.rb
Rails.application.configure do
config.active_storage.previewers << HeicPreviewer
config.active_storage.variable_content_types << "image/heic"
config.active_storage.variable_content_types << "image/heif"
end
# test/previewers/heic_previewer_test.rb
require "test_helper"
class HeicPreviewerTest < ActiveSupport::TestCase
include ActiveStorageBlob
CONTENT_TYPE = "image/heic"
test "it previews a heic image" do
skip "it does not run on CI due to missing support for HEIC" if ENV["CI"] == "true"
blob = create_file_blob(filename: "heic-image-file.heic", content_type: CONTENT_TYPE)
refute_nil blob
assert HeicPreviewer.accept?(blob)
HeicPreviewer.new(blob).preview({}) do |attachable|
assert_equal "image/png", attachable[:content_type]
end
end
end
create_file_blog
method is a helper that I use to create an Active Storage blob object from a file. The test is simple; it tests that previewing or downloading a file get converted to PNG.$ heroku buildpacks:add [https://github.com/HiMamaInc/heroku-buildpack-imagemagick-heif](https://github.com/HiMamaInc/heroku-buildpack-imagemagick-heif) --index 1
34