Class: Zena::Use::ImageBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/zena/use/image_builder.rb

Constant Summary collapse

DEFAULT_FORMATS =
{
  'tiny'  => { :name=>'tiny', :size=>:force, :width=>16,  :height=>16 , :gravity=>Magick::CenterGravity   },
  'tipop' => { :name=>'tipop', :size=>:force, :width=>16,  :height=>16 , :gravity=>Magick::CenterGravity,
    :popup => {
        :name    => 'std',
        :options => {'title' => 'link'},
        :show    => ['navigation','title','summary']
      }
  },
  'mini' =>   { :name=>'mini', :size=>:force, :width=>32,  :height=>32 , :gravity=>Magick::CenterGravity   },
  'square' => { :name=>'square', :size=>:limit, :width=>180, :height=>180, :gravity=>Magick::CenterGravity },
  'med'  =>   { :name=>'med',  :size=>:limit, :width=>280, :height=>186, :gravity=>Magick::CenterGravity   },
  'top'  =>   { :name=>'top',  :size=>:force, :width=>280, :height=>186, :gravity => Magick::NorthGravity  },
  'low'  =>   { :name=>'low',  :size=>:force, :width=>280, :height=>186, :gravity => Magick::SouthGravity  },
  'side' =>   { :name=>'side', :size=>:force, :width=>220, :height=>500, :gravity=>Magick::CenterGravity   },
  'std'  =>   { :name=>'std',  :size=>:limit, :width=>600, :height=>400, :gravity=>Magick::CenterGravity   },
  'pv'   =>   { :name=>'pv',   :size=>:force, :width=>70,  :height=>70 , :gravity=>Magick::CenterGravity   },
  'edit' =>   { :name=>'edit', :size=>:limit, :width=>400, :height=>400, :gravity=>Magick::CenterGravity   },
  'full' =>   { :name=>'full', :size=>:keep                            , :gravity=>Magick::CenterGravity   },
  nil    =>   { :name=>'full', :size=>:keep                            , :gravity=>Magick::CenterGravity   },
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(h) ⇒ ImageBuilder

Returns a new instance of ImageBuilder.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/zena/use/image_builder.rb', line 81

def initialize(h)
  params = {:height=>nil, :width=>nil, :path=>nil, :file=>nil, :actions=>[]}.merge(h)
  node = params.delete(:node)

  params.each do |k,v|
    case k
    when :height
      @height = v if v
    when :width
      @width = v if v
    when :path
      @path = v if v
    when :file
      @file = v if v
    when :actions
      if v.kind_of?(Array)
        @actions = v
      else
        raise StandardError, "Bad actions format"
      end
    else
      raise StandardError, "Bad parameter (#{k})"
    end
  end
  unless @width && @height || dummy?
    if @img = build_image_from_file_or_path
      @width  = @img.columns
      @height = @img.rows
      if node && node.respond_to?(:fix_sizes)
        # Fix property
        node.fix_sizes(@width, @height)
      end
    end
  end
end

Class Method Details

.dummy?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/zena/use/image_builder.rb', line 67

def dummy?
  Magick.const_defined?(:ZenaDummy)
end

.hash_id(format) ⇒ Object



71
72
73
# File 'lib/zena/use/image_builder.rb', line 71

def hash_id(format)
  Digest::SHA1.hexdigest("#{format[:name]}#{format[:size]}#{format[:width]}#{format[:height]}#{format[:gravity]}")[0..9].to_i(16)
end

.image_content_type?(content_type) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/zena/use/image_builder.rb', line 63

def image_content_type?(content_type)
  content_type =~ /image/ && !(content_type =~ /svg/)
end

Instance Method Details

#build_image_from_file_or_pathObject



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/zena/use/image_builder.rb', line 324

def build_image_from_file_or_path
  if @file || @path
    if @file.kind_of?(StringIO)
      img = Magick::ImageList.new
      @file.rewind
      img.from_blob(@file.read)
      @file.rewind
      @filesize = @file.size
      img
    else
      img = Magick::ImageList.new(@file ? @file.path : @path)
      @filesize = img.filesize
      img
    end
  end
rescue
  nil
end

#columnsObject Also known as: width



138
139
140
141
# File 'lib/zena/use/image_builder.rb', line 138

def columns
  return nil unless @width || !dummy?
  (@width ||= render_img.columns).round
end

#crop!(x, y, w, h) ⇒ Object



155
156
157
158
159
160
# File 'lib/zena/use/image_builder.rb', line 155

def crop!(x,y,w,h)
  @img = nil # reset current rendered image
  @width  = [@width -x, w].min
  @height = [@height-y, h].min
  @actions << Proc.new {|img| img.crop!(x,y,[@img.columns-x, w].min,[@img.rows-y, h].min, true) }
end

#crop_min!(w, h, gravity = Magick::CenterGravity) ⇒ Object



207
208
209
210
211
212
# File 'lib/zena/use/image_builder.rb', line 207

def crop_min!(w,h,gravity=Magick::CenterGravity)
  @img = nil # reset current rendered image
  @width  = [@width ,w].min
  @height = [@height,h].min
  @actions << Proc.new {|img| img.crop!(gravity,[@img.columns,w].min,[@img.rows,h].min, true) }
end

#do_limit!(size) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/zena/use/image_builder.rb', line 179

def do_limit!(size)
  return @img if @filesize <= size

  # Check real size
  tmp_path = Tempfile.new('tmp_img').path
  @img.write('jpeg:' + tmp_path)

  return @img if File.stat(tmp_path).size <= size

  # Change type to JPG and quality to 80
  if (@img.format == 'JPG' || @img.format == 'JPEG') && @img.quality > 80
    @img.write('jpeg:' + tmp_path) { self.quality = 80 }
  else
    @img.format = 'JPG'
    @img.write('jpeg:' + tmp_path) { self.quality = 80 }
  end
  ratio = File.stat(tmp_path).size.to_f / size

  return @img = Magick::ImageList.new(tmp_path) if ratio <= 1.0

  # Not enough ? Resize.
  ratio   = 1.0 / Math.sqrt(ratio)
  @width  *= ratio
  @height *= ratio
  @img.resize!(ratio)
  @img
end

#dummy?Boolean

Returns:

  • (Boolean)


117
118
119
# File 'lib/zena/use/image_builder.rb', line 117

def dummy?
  Zena::Use::ImageBuilder.dummy? || (!@path && !@img && !@file)
end

#exifObject



171
172
173
# File 'lib/zena/use/image_builder.rb', line 171

def exif
  @exif ||= ExifData.new(render_img.get_exif_by_entry)
end

#formatObject



167
168
169
# File 'lib/zena/use/image_builder.rb', line 167

def format
  render_img.format
end

#format=(fmt) ⇒ Object



162
163
164
165
# File 'lib/zena/use/image_builder.rb', line 162

def format=(fmt)
  return if dummy? || !Magick.formats[fmt.upcase] =~ /w/
  @actions << Proc.new {|img| img.format = fmt.upcase; img }
end

#max_filesize=(size) ⇒ Object



175
176
177
# File 'lib/zena/use/image_builder.rb', line 175

def max_filesize=(size)
  @actions << Proc.new {|img| do_limit!(size) }
end

#readObject



121
122
123
124
125
# File 'lib/zena/use/image_builder.rb', line 121

def read
  return nil if dummy?
  render_img
  @img.to_blob
end

#render_imgObject

Raises:

  • (IOError)


295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/zena/use/image_builder.rb', line 295

def render_img
  raise IOError, 'MagickDummy cannot render image' if Zena::Use::ImageBuilder.dummy?
  unless @img
    unless @img = build_image_from_file_or_path
      raise IOError, 'Cannot render image without path or file'
    end
    if @pre
      @pre = [@pre].flatten
      @pre.each do |a|
        @img = a.call(@img)
      end
    end

    if @actions
      @actions.each do |a|
        @img = a.call(@img)
      end
    end

    if @post
      @post = [@post].flatten
      @post.each do |a|
        @img = a.call(@img)
      end
    end
  end
  @img
end

#resize!(s) ⇒ Object



146
147
148
149
150
151
152
153
# File 'lib/zena/use/image_builder.rb', line 146

def resize!(s)
  # we do not zoom pixels
  return unless s < 1.0
  @img = nil # reset current rendered image
  @width  *= s
  @height *= s
  @actions << Proc.new {|img| img.resize!(s) }
end

#rowsObject Also known as: height



133
134
135
136
# File 'lib/zena/use/image_builder.rb', line 133

def rows
  return nil unless @height || !dummy?
  (@height ||= render_img.rows).round
end

#set_background!(opacity, w, h) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
# File 'lib/zena/use/image_builder.rb', line 214

def set_background!(opacity,w,h)
  @img = nil # reset current rendered image
  @width  = [@width ,w].max
  @height = [@height,h].max
  @actions << Proc.new do |img|
    bg = Magick::Image.new(w,h)
    bg.opacity = opacity
    bg.format = img.format
    img = bg.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)
  end
end

#transform!(tformat = nil) ⇒ Object

Transform into another format. If nil : do nothing.



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/zena/use/image_builder.rb', line 227

def transform!(tformat=nil)
  return self unless tformat
  @img = nil
  format = { :size=>:limit, :gravity=>Magick::CenterGravity }.merge(tformat)
  @pre, @post = format[:pre], format[:post]

  if format[:size] == :keep
    h,w = @height, @width
  else
    h,w = format[:height], format[:width]
  end
  if format[:scale]
    if h || w
      # scale is a pre-zoom before crop
      scale = format[:scale]
    else
      # we resize to scale
      h,w = @height*format[:scale], @width*format[:scale]
      # but we do not zoom
      scale = 1.0
      # ignore ':size' format if not height nor width was given
      format[:size] = :force
    end
  else
    scale = 1.0
  end
  if format[:ratio] && h && !w
    w = h / format[:ratio]
  elsif format[:ratio] && w && !h
    h = w * format[:ratio]
  end

  pw,ph = @width, @height
  if [w,h,pw,ph].include?(nil) || [w,h,pw,ph].min <= 0
    # image size or thumb size is null (no image processing tool used, no idea on image size)
    if format[:size] == :keep
      @height, @width = nil, nil
    else
      @height, @width = h, w
    end
    return self
  end

  case format[:size]
  when :force
    crop_scale = [w.to_f/pw, h.to_f/ph].max
    if crop_scale > 1.0
      # we do not zoom. Fill with transparent background.
      crop_min!(w,h,format[:gravity])
      set_background!(Magick::MaxRGB, w, h)
    else
      resize!(crop_scale * scale)
      crop_min!(w, h,format[:gravity])
    end
  when :force_no_crop
    crop_scale = [w.to_f/pw, h.to_f/ph].min
    resize!(crop_scale * scale)
    crop_min!(w, h,format[:gravity])
    set_background!(Magick::MaxRGB, w, h)
  when :limit
    crop_scale = [w.to_f/pw, h.to_f/ph].min
    resize!(crop_scale * scale)
    crop_min!(w, h,format[:gravity])
  when :keep
  end
  self
end

#write(path) ⇒ Object



127
128
129
130
131
# File 'lib/zena/use/image_builder.rb', line 127

def write(path)
  return false if dummy?
  render_img
  @img.write(path)
end