Skip to content

Commit

Permalink
Apply a diet on uploaded images
Browse files Browse the repository at this point in the history
  • Loading branch information
mdouchement committed Jul 12, 2020
1 parent 3341db0 commit 83963bd
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 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
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 83963bd

Please sign in to comment.