OSDN Git Service

1bf90217b25bf5f3800c6a7dd9d9adc36e2bfae3
[pettanr/pettanr.git] / app / models / resource_picture.rb
1 class ResourcePicture < ActiveRecord::Base
2   belongs_to :artist
3   belongs_to :lisence
4   has_many :panel_pictures
5   belongs_to :original_picture
6   
7   def self.resize(data, dw, dh)
8     Magick::Image.from_blob(data).shift.resize(dw, dh)
9   end
10   
11   #サイズの調整(limw,limhに必ず収まるように合わせる)
12   def self.fix_size_both(limw, limh, w, h)
13     wr = if w > limw
14       limw*100/w
15     else
16       100
17     end
18     hr = if h > limh
19       limh*100/h
20     else
21       100
22     end
23     res = if wr < hr
24       #幅の方が圧縮率が高い
25       [w*wr/100, h*wr/100]
26     else
27       #高さの方が圧縮率が高い
28       [w*hr/100, h*hr/100]
29     end
30     res
31   end
32   
33   def dext
34     self.ext.downcase
35   end
36   
37   def filename
38     "#{self.id}.#{self.dext}"
39   end
40   
41   def mime_type
42     "image/#{self.dext}"
43   end
44   
45   def v(rimg)
46     rimg.flip.to_blob
47   end
48   
49   def h(rimg)
50     rimg.flop.to_blob
51   end
52   
53   def vh(rimg)
54     rimg.flip.flop.to_blob
55   end
56   
57   def url subdir = nil
58     '/resource_pictures/' + (subdir.to_s.empty? ? '' : subdir.to_s + '/' ) + filename
59   end
60   
61   def thumbnail(rimg)
62     tw, th = ResourcePicture.fix_size_both(80, 80, rimg.columns, rimg.rows)
63     ResourcePicture.resize(rimg.to_blob, tw, th).to_blob
64   end
65   
66   def self.store(img, original_picture)
67     
68     resource_picture = ResourcePicture.new(
69       width: original_picture.width, height: original_picture.height, 
70       ext: original_picture.ext, filesize: original_picture.filesize, 
71       original_picture_id: original_picture.id
72     )
73     res = if resource_picture.save
74       if resource_picture.store(img)
75         true
76       else
77         false
78       end
79     else
80       false
81     end
82     res
83   end
84   
85   def store(img)
86     res = false
87     bindata = img.to_blob
88 #    begin
89       PictureIO.resource_picture_io.put bindata, self.filename
90       PictureIO.resource_picture_io.class.subdirs.each do |d|
91         next if d.empty?
92         PictureIO.resource_picture_io.put(self.__send__(d, img), self.filename, d)
93       end
94       res = true
95 #    rescue
96 #      res = false
97 #    end
98     res
99   end
100   
101   def restore(subdir = nil)
102     PictureIO.resource_picture_io.get self.filename, subdir
103   end
104   
105 end