socialforge/lib/trustie/utils/image.rb

61 lines
1.3 KiB
Ruby
Raw Normal View History

2015-05-08 14:28:17 +08:00
#coding=utf-8
module Trustie
module Utils
class Image
def initialize(file, bak=false)
2015-05-08 14:28:17 +08:00
@file = file
@bak = bak
end
def bitmap?(data)
data[0,2]==77.chr + 66.chr
end
def gif?(data)
data[0,4]==71.chr + 73.chr + 70.chr + 56.chr
end
def jpeg?(data)
2015-05-24 13:52:27 +08:00
data[0,3]== 0xff.chr + 0xd8.chr + 0xff.chr
end
def png?(data)
data[0,2]==0x89.chr + 80.chr
end
def image?
2015-05-24 13:52:27 +08:00
data = ''
if @file.respond_to?(:read)
data = @file.read(9)
@file.rewind
end
2015-05-24 13:52:27 +08:00
return false if data.size < 9
bitmap?(data) || gif?(data) || jpeg?(data) || png?(data)
end
2015-05-08 14:28:17 +08:00
def compress(size=300)
backup if @bak
begin
f = Magick::ImageList.new(@file)
if f.format != 'GIF'
width = size
if f[0].columns > width
proportion = (width/f[0].columns.to_f)
height = (f[0].rows*proportion)
f.resize_to_fill!(width,height.to_i)
f.write(@file)
end
end
rescue Exception => e
Rails.logger.error "[Error] compress : ===> #{e}"
2015-05-08 14:28:17 +08:00
end
end
def backup
FileUtils.cp @file, "#{@file}.bak"
end
end
end
end