当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - RMagick - how to create a thumbnail with an automatic height?

问题描述:

I am using RMagick for creating thumbnails like this:

 img = Magick::Image.read(image_url).first

target = Magick::Image.new(110, 110) do

self.background_color = 'white'

end

img.resize_to_fit!(110, 110)

target.composite(img, Magick::CenterGravity, Magick::CopyCompositeOp).write(thumb_path)

This works well - I'll load the current image, create a "space" for the new thumb and then will place it there.

However, I would need to create a thumb where would be the width 110px and the height would be automatically counted... How to do this?

Thank you

网友答案:

You'd rather use resize_to_fill!

Doc here

网友答案:
image = Magick::Image.read(image_url).first
image.format = "JPG"
image.change_geometry!("110X110") { |cols, rows| image.thumbnail! cols, rows }
image.write("<path to save thumbnail>")
网友答案:

This turns out to be super easy! ImageMagick and GraphicsMagick both maintain aspect ratios properly, so in your case, just give the max width you want the image to be. See http://www.imagemagick.org/script/command-line-processing.php#geometry to learn more about the magick dimension operators.

If you find that you're ruby process' RAM consumption is growing, you may want to switch to an external-exec image library, like https://github.com/mceachen/micro_magick. Also, switching to GraphicsMagick is an all-around win, BTW, giving better image encoding and in less time.

require 'micro_magick'
img = MicroMagick::Convert.new("input.png")
img.resize("110") # this restricts to width, if you want to restrict to height, use "x345"
img.unsharp(1.5) # This runs an "unsharp mask" convolution filter, and is optional
img.write("output.png")
分享给朋友:
您可能感兴趣的文章:
随机阅读: