This code snippet uses MiniMagick to open a PNG image, reduce its quality to 50 and save the compressed image with a new file name.
require 'mini_magick' # open the input file input_file = MiniMagick::Image.open('input.png') # compress the image with quality 50 input_file.quality(50) # save the output file input_file.write('output.png')
Let's break down each part of the code:
require 'mini_magick': This line imports the MiniMagick gem into your Ruby script. MiniMagick is a popular Ruby library for interacting with the ImageMagick command-line tools, which allows you to manipulate images programmatically.
input_file = MiniMagick::Image.open('input.png'): This line opens an image file named 'input.png' using MiniMagick and assigns it to the variable
input_file. This step essentially loads the image into memory, making it accessible for further processing.
input_file.quality(50): Here, you are specifying a quality setting of 50 for the image. This quality setting applies to image formats like JPEG, where you can control the compression level by adjusting the quality. A lower quality value (e.g., 50) typically results in a smaller file size but may also reduce the image's visual quality.
input_file.write('output.png'): Finally, this line saves the modified image, which has been compressed with the specified quality setting, as 'output.png'. The
writemethod is used to save the image with the specified changes.