Rmagick compresses when file size is greater than X without writing (upload to S3)

I would like to compress the image when its size is larger than the sum (i.e. 1,000,000 - 1 MB). I see that compression is used with the write method in the Image object. I have an image in memory and I do not want to write it on my server, but on Amazon S3.

This code works. It uploads the image to my s3 path, however I would like to enable size checking and compression:

photo = Magick::Image.read(mmkResourceImage.href).first           
s3 = AWS::S3.new      
bucket = s3.buckets[bucketName]            
obj = bucket.objects[key]    
obj.write(photo)

Please let me know if there is another approach for this.

+4
source share
1 answer

, Magick:: Image # to_blob, . String # bytesize. : ....

, 75%, 1 000 000 .

while photo.to_blob.bytesize > 1_000_000
  photo.scale!(0.75)
end

,

(0..100).step(5).reverse_each do |quality|
  blob = photo.to_blob { self.quality = quality }

  if blob.bytesize <= 1_000_000
    photo = Magick::Image.from_blob(blob).first
    break
  end  
end 
+1

Source: https://habr.com/ru/post/1614486/


All Articles