Class: FastImage

Inherits:
Object
  • Object
show all
Defined in:
lib/fastimage_resize.rb

Defined Under Namespace

Classes: FormatNotSupported

Constant Summary collapse

SUPPORTED_FORMATS =
[:jpeg, :png, :gif]
FILE_EXTENSIONS =

prefer jpg to jpeg as an extension

[:jpg, :png, :gif]

Class Method Summary collapse

Class Method Details

.resize(input, w, h, options = {}) ⇒ Object

Resizes an image, storing the result in a file given in file_out

Input can be a filename, a uri, or an IO object.

FastImage Resize can resize GIF, JPEG and PNG files.

Giving a zero value for width or height causes the image to scale proportionately.

Example

require 'fastimage_resize'

FastImage.resize("http://stephensykes.com/images/ss.com_x.gif", 100, 20, :outfile=>"my.gif")

Supported options

:jpeg_quality

A figure passed to libgd to determine quality of output jpeg (only useful if input is jpeg)

:outfile

Name of a file to store the output in, in this case a temp file is not used



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/fastimage_resize.rb', line 61

def self.resize(input, w, h, options={})
  jpeg_quality = options[:jpeg_quality] || -1
  file_out = options[:outfile]
  
  if input.respond_to?(:read)
    file_in = read_to_local(input)
  else
    u = URI.parse(input)
    if u.scheme == "http" || u.scheme == "https" || u.scheme == "ftp"
      file_in = read_to_local(open(u))
    else
      file_in = input.to_s
    end
  end

  fast_image = new(file_in, :raise_on_failure=>true)
  type_index = SUPPORTED_FORMATS.index(fast_image.type)
  raise FormatNotSupported unless type_index

  if !file_out
    temp_file = Tempfile.new([name, ".#{FILE_EXTENSIONS[type_index]}"])
    temp_file.binmode
    file_out = temp_file.path
  else
    temp_file = nil
  end

  in_path = file_in.respond_to?(:path) ? file_in.path : file_in

  fast_image.resize_image(in_path, file_out.to_s, w.to_i, h.to_i, type_index, jpeg_quality.to_i)

  if file_in.respond_to?(:close)
    file_in.close
    file_in.unlink
  end

  temp_file
rescue OpenURI::HTTPError, SocketError, URI::InvalidURIError, RuntimeError => e
  raise ImageFetchFailure, e.class
end