OSDN Git Service

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