Search code examples
rubyamazon-s3rmagick

Rmagick compress when filesize is bigger than X without write (upload to S3)


I would like to compress an image when its size is bigger than an amount (i.e. 1000000 - 1MB). I see compress is used with write method in Image object. I have the image in memory and I don´t want to write it in my server but in an Amazon S3.

This code is working. It´s uploading the image to my s3 path, however I would like to include the filesize check and the compress:

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 to accomplish this.


Solution

  • To get the current size you can use Magick::Image#to_blob which will return a binary string. You can get the string's size with String#bytesize. You can scale it down with Magick::Image#scale!.

    Here is an example that would resize it by 75% until it was under a 1,000,000 bytes.

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

    Here is an example that would reduce the quality instead

    (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