使用imagemagick的格式字符串和宽度/高度计算新的图像大小

时间:2011-10-05 16:01:19

标签: imagemagick image-scaling

在网络应用中,最好使用img标签的width和height属性 - 这样浏览器就可以更快地呈现页面。

如果我有图像的宽度和高度,以及imagemagick格式字符串(即'300>'),我怎样才能获得该图像调整大小的大小?我希望imagemagick有一些钩子/函数可以让我访问这些信息。

我不想调整大小或将图片加载到内存中,我只是想知道尺寸是多少。

基本上,我想要以下功能:

def get_image_size(width, height, format_string)
  # ... magic here
  return [new_width, new_height]
end

width, height = get_image_size(300, 400, '235x235!')
# would return 235 and 235

width, height = get_image_size(300, 400, '700x700>')
# would return 300 and 400

width, height = get_image_size(300, 400, '100x100')
# would return 75 and 100

1 个答案:

答案 0 :(得分:3)

使用以下ImageMagick convert命令可以提供您想要的内容。这应该很容易转换为您选择的ImageMagick language API

$ convert -size 300x400 xc:white -resize '235x235!' info:- | cut -d\  -f3
235x235
$ convert -size 300x400 xc:white -resize '700x700>' info:- | cut -d\  -f3
300x400
$ convert -size 300x400 xc:white -resize '100x100' info:- | cut -d\  -f3
75x100