「ruby/MiniMagick」用MiniMagick处理图片

包的选择和配置

想用RMagick,但据说内存泄露的问题比较厉害,作为替代品MiniMagick不存在内存泄露的问题。而二者都是使用ImageMagick的,所以需要下载并安装ImageMagick

下面安装ImageMagick:

sudo apt-get install imagemagick

安装gem··「mini_magick」

gem  install mini_magick --no-ri --no-rdoc

测试和使用mini_magick

引入gem MiniMagick :

require "mini_magick"

MiniMagick中的Image对象

MiniMagick::Image

from_file(file, ext = nil)

 

img=MiniMagick::Image.open("./pic1.jpg")

 

[](value)

A rather low-level way to interact with the “identify” command. No nice API here, just the crazy stuff you find in ImageMagick. See the examples listed!

@example

image["format"]      #=> "TIFF"
image["height"]      #=> 41 (pixels)
image["width"]       #=> 50 (pixels)
image["dimensions"]  #=> [50, 41]
image["size"]        #=> 2050 (bits)
image["original_at"] #=> 2005-02-23 23:17:24 +0000 (Read from Exif data)
image["EXIF:ExifVersion"] #=> "0220" (Can read anything from Exif)

@param format [String] A format for the “identify” command @see For reference seewww.imagemagick.org/script/command-line-options.php#format @return [String, Numeric, Array, Time, Object] Depends on the method called! Defaults to String for unknown commands

write(output_to)

Writes the temporary file out to either a file location (by passing in a String) or by passing in a Stream that you can write(chunk) to repeatedly

@param output_to [IOStream, String] Some kind of stream object that needs to be read or a file path as a String @return [IOStream, Boolean] If you pass in a file location [String] then you get a success boolean. If its a stream, you get it back. Writes the temporary image that we are using for processing to the output path

shave("宽x高")

require ‘mini_magick’
img = MiniMagick::Image.from_file “1.jpg”

w,h = img[:width],img[:height] #=> [2048, 1536]#取得宽度和高度
shaved_off = ((w-h)/2).round #=> 256
img.shave “#{shaved_off}x0″ #此处表示宽度上左右各截取256个像素,高度上截取0像素

img.write “2.jpg”
#!/usr/bin/ruby

require "mini_magick"

def  resize_and_crop(image, square_size) 
	if image[:width]<image[:height]
		shave_off=((image[:height]-image[:width])/2).round
		image.shave("0x#{shave_off}")
	elsif image[:width]>image[:height]
		shave_off=((image[:width]-image[:height])/2).round
	end
	geometry=to_geometry(square_size,square_size)
	image.resize(geometry
	return image
end

new_image=resize_and_crop(MiniMagick::Image.from_file("1.jpg"))

 

 

 

 

 

 

 

posted @ 2014-04-19 09:33  怒杀神  阅读(1364)  评论(0编辑  收藏  举报