]> git.openstreetmap.org Git - rails.git/blob - lib/avatar_normaliser.rb
Merge remote-tracking branch 'upstream/pull/7618'
[rails.git] / lib / avatar_normaliser.rb
1 # frozen_string_literal: true
2
3 # Re-encodes uploaded avatars, to avoid storing the original file.
4 # The result has limited dimensions (and therefore filesize),
5 # has only the first frame of any animation,
6 # and has all metadata (such as EXIF location) stripped.
7 module AvatarNormaliser
8   # Maximum width and height of a normalised avatar
9   MAX_DIMENSION = 512
10
11   # Returns an attachable hash for the normalised image. Raises Vips::Error
12   # if the image can't be processed.
13   def self.normalise(io, content_type)
14     io.rewind
15     image = Vips::Image.new_from_buffer(io.read, "").autorot
16     image = image.icc_transform("srgb", :embedded => true) if image.get_typeof("icc-profile-data").nonzero?
17
18     format = if ActiveStorage.web_image_content_types.include?(content_type)
19                Marcel::Magic.new(content_type).extensions.first
20              else
21                "png"
22              end
23
24     file = ImageProcessing::Vips.source(image)
25                                 .resize_to_limit(MAX_DIMENSION, MAX_DIMENSION)
26                                 .saver(:strip => true)
27                                 .convert(format)
28                                 .call
29
30     { :io => file, :filename => "avatar.#{format}" }
31   end
32 end