merged/app/models/merged/image.rb

103 lines
2.8 KiB
Ruby

require "mini_magick"
require "fileutils"
module Merged
class Image < ActiveBase
set_root_path Rails.root
fields :name , :tags , :type , :size , :height , :width
def change_name
name
end
def aspect_ratio
ratio = self.ratio
ratios = (1..9).collect{ |i| ((ratio * i) - (ratio * i).round(0)).abs }
min , min_index = ratios.each_with_index.min
[(ratio * (min_index + 1) ).round(0).to_i , (min_index + 1) ]
end
def ratio
return 0 unless self.height
self.width.to_f / self.height
end
def copy()
image = Image.new name: "#{name}_copy" , type: type , tags: (tags || "") ,
width: width , height: height, size: size
Image.insert(image) # assigns next id
FileUtils.cp full_filename , image.full_filename
image
end
def scale( new_size )
mini = MiniMagick::Image.new( full_filename)
mini.resize( new_size.to_s + "%")
init_file_size
end
def crop( to_size )
mini = MiniMagick::Image.new(full_filename)
mini.crop( to_size )
init_file_size
end
#save an io as new image. The filename is the id, type taken from io
def self.create_new(name , tags, io)
original , end_ = io.original_filename.split("/").last.split(".")
magick_image = MiniMagick::Image.read(io)
ending = magick_image.type.downcase
ending = "jpg" if ending == "jpeg"
name = original if( name.blank? )
image = Image.new name: name , type: ending , tags: (tags || "") ,
width: magick_image.width, height: magick_image.height ,
size: (magick_image.size/1024).to_i
self.insert(image) # assigns next id
full_filename = image.id.to_s + "." + ending
magick_image.write(Rails.root.join(Image.asset_root, full_filename))
image
end
def destroy(editor)
File.delete self.full_filename
delete_save!(editor)
end
def asset_name
Merged.images_dir + "/" + self.id.to_s + "." + self.type
end
def full_filename
full_filename = self.id.to_s + "." + self.type
Rails.root.join(Image.asset_root, full_filename)
end
def self.transform
Image.all.each do |image|
last = image.name.split.last
image.tags = ""
["wide", "small" , "big" , "room"].each do |tag|
if(last == tag)
image.name = image.name.gsub(last,"").strip
image.tags = last
end
end
image.save
end
end
def init_file_size
magick_image = MiniMagick::Image.open(full_filename)
self.width = magick_image.width
self.height = magick_image.height
self.size = (magick_image.size/1024).to_i
end
def self.asset_root
"app/assets/images/" + Merged.images_dir
end
end
end