Compress JPEG Image Files Using Ruby
This code snippet opens a JPEG image, reduces its quality to 50 and then saves the compressed image as a new file.
This code snippet opens a JPEG image, reduces its quality to 50 (which increases compression and reduces file size) and then saves the compressed image with the same filename.
require 'mini_magick'
# open the input file
input_file = MiniMagick::Image.open('input.jpg')
# compress the image with quality 50
input_file.quality(50)
# save the output file
input_file.write('output.jpg')
Let's break down each part of the code:
require 'mini_magick'
# open the input file
input_file = MiniMagick::Image.open('input.jpg')
- This line includes the MiniMagick gem in your Ruby script.
- It then opens an image file named 'input.jpg' using MiniMagick and assigns it to the variable
input_file
. This step loads the JPEG image into memory for further processing.
# compress the image with quality 50
input_file.quality(50)
- This line sets the quality of the opened JPEG image to 50. In JPEG compression, the quality parameter typically ranges from 0 to 100, with higher values indicating better quality but larger file sizes. Lower values, such as 50, result in greater compression and smaller file sizes but may reduce image quality.
# save the output file
input_file.write('output.jpg')
- Finally, this line saves the modified JPEG image, which has been compressed with a quality setting of 50, as 'output.jpg'. The
write
method is used to save the image with the specified changes.