Skip to content

Commit

Permalink
Merge pull request #324 from FranckKe/tp-storage_diet
Browse files Browse the repository at this point in the history
[master] Apply a diet on uploaded images
  • Loading branch information
FranckKe authored Jul 17, 2020
2 parents 771ae61 + 32ac796 commit 86342a6
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 5 deletions.
30 changes: 26 additions & 4 deletions app/contexts/uploads.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,33 @@ def initialize(data_uri)

def call
data_uri_parts = data_uri.match(REGEXP) || {}
ext = ((data_uri_parts[:type] || '').match(EXT) || {})[:ext] || '.png'
{
io: StringIO.new(Base64.decode64(data_uri_parts[:content] || '')),
content_type: data_uri_parts[:type],
filename: "#{SecureRandom.uuid}.#{ext}"
io: diet(Base64.decode64(data_uri_parts[:content] || '')),
content_type: 'image/jpeg',
filename: "#{SecureRandom.uuid}.jpg"
}
end

private

def diet(content)
return StringIO.new('') if content.empty?

original = Tempfile.new('mersea.uploaded', binmode: true)
original << content
original.close

processed = ImageProcessing::MiniMagick
.source(original.path)
.resize_to_limit(1920, 1080)
.quality(90)
.convert("jpg")
.call(save: true)

StringIO.new(processed.read)
ensure
original&.unlink
processed&.close
processed&.unlink
end
end
2 changes: 1 addition & 1 deletion config/initializers/filter_parameter_logging.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Be sure to restart your server when you modify this file.

# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
Rails.application.config.filter_parameters += [:password, :photo]
22 changes: 22 additions & 0 deletions lib/tasks/diet_photo.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace :storage do
desc 'Diet all images'
task diet: :environment do
ActiveStorage::Attachment.find_each.each do |attachment|
next if attachment.name != "photo"
puts "Attachement #{attachment.id}"

path = ActiveStorage::Blob.service.send(:path_for, attachment.key)
puts " path: #{path}"
puts " size: #{File.size(path)}"

ImageProcessing::MiniMagick
.source(path)
.resize_to_limit(1920, 1080)
.quality(90)
.convert("jpg")
.call(save: true, destination: path)

puts " newsize: #{File.size(path)}"
end
end
end

0 comments on commit 86342a6

Please sign in to comment.