pax_global_header 0000666 0000000 0000000 00000000064 13534264000 0014507 g ustar 00root root 0000000 0000000 52 comment=d1e49be9fcce5f9acf160072631fc844cb84c51b fastimage-2.1.7/ 0000775 0000000 0000000 00000000000 13534264000 0013456 5 ustar 00root root 0000000 0000000 fastimage-2.1.7/.gitignore 0000664 0000000 0000000 00000000022 13534264000 0015440 0 ustar 00root root 0000000 0000000 pkg/ Gemfile.lock fastimage-2.1.7/.travis.yml 0000664 0000000 0000000 00000000304 13534264000 0015564 0 ustar 00root root 0000000 0000000 language: ruby rvm: - 2.2.9 - 2.3.8 - 2.4.5 - 2.5.5 - 2.6.2 sudo: false # uncomment this line if your project needs to run something other than `rake`: # script: bundle exec rspec spec fastimage-2.1.7/Gemfile 0000664 0000000 0000000 00000000046 13534264000 0014751 0 ustar 00root root 0000000 0000000 source 'https://rubygems.org' gemspec fastimage-2.1.7/MIT-LICENSE 0000664 0000000 0000000 00000002046 13534264000 0015114 0 ustar 00root root 0000000 0000000 Copyright (c) 2008-2013 Stephen Sykes Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fastimage-2.1.7/README.textile 0000664 0000000 0000000 00000016711 13534264000 0016021 0 ustar 00root root 0000000 0000000 !https://img.shields.io/gem/dt/fastimage.svg!:https://rubygems.org/gems/fastimage !https://travis-ci.org/sdsykes/fastimage.png?branch=master!:https://travis-ci.org/sdsykes/fastimage h1. FastImage h4. FastImage finds the size or type of an image given its uri by fetching as little as needed h2. The problem Your app needs to find the size or type of an image. This could be for adding width and height attributes to an image tag, for adjusting layouts or overlays to fit an image or any other of dozens of reasons. But the image is not locally stored - it's on another asset server, or in the cloud - at Amazon S3 for example. You don't want to download the entire image to your app server - it could be many tens of kilobytes, or even megabytes just to get this information. For most common image types (GIF, PNG, BMP etc.), the size of the image is simply stored at the start of the file. For JPEG files it's a little bit more complex, but even so you do not need to fetch much of the image to find the size. FastImage does this minimal fetch for image types GIF, JPEG, PNG, TIFF, BMP, ICO, CUR, PSD, SVG and WEBP. And it doesn't rely on installing external libraries such as RMagick (which relies on ImageMagick or GraphicsMagick) or ImageScience (which relies on FreeImage). You only need supply the uri, and FastImage will do the rest. h2. Features FastImage can also read local (and other) files - anything that is not parseable as a URI will be interpreted as a filename, and FastImage will attempt to open it with @File#open@. FastImage will also automatically read from any object that responds to @:read@ - for instance an IO object if that is passed instead of a URI. FastImage will follow up to 4 HTTP redirects to get the image. FastImage will obey the @http_proxy@ setting in your environment to route requests via a proxy. You can also pass a @:proxy@ argument if you want to specify the proxy address in the call. You can add a timeout to the request which will limit the request time by passing @:timeout => number_of_seconds@. FastImage normally replies with @nil@ if it encounters an error, but you can pass @:raise_on_failure => true@ to get an exception. FastImage also provides a reader for the content length header provided in HTTP. This may be useful to assess the file size of an image, but do not rely on it exclusively - it will not be present in chunked responses for instance. FastImage accepts additional HTTP headers. This can be used to set a user agent or referrer which some servers require. Pass an @:http_header@ argument to specify headers, e.g., @:http_header => {'User-Agent' => 'Fake Browser'}@. FastImage can give you information about the parsed display orientation of an image with Exif data (jpeg or tiff). FastImage also handles "Data URIs":https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs correctly. h2. Security As of v1.6.7 FastImage no longer uses @openuri@ to open files, but directly calls @File.open@. Take care to sanitise the strings passed to FastImage; it will try to read from whatever is passed. h2. Examples
require 'fastimage'
FastImage.size("http://stephensykes.com/images/ss.com_x.gif")
=> [266, 56] # width, height
FastImage.type("http://stephensykes.com/images/pngimage")
=> :png
FastImage.type("/some/local/file.gif")
=> :gif
FastImage.size("http://upload.wikimedia.org/wikipedia/commons/b/b4/Mardin_1350660_1350692_33_images.jpg", :raise_on_failure=>true, :timeout=>0.1)
=> FastImage::ImageFetchFailure: FastImage::ImageFetchFailure
FastImage.size("http://upload.wikimedia.org/wikipedia/commons/b/b4/Mardin_1350660_1350692_33_images.jpg", :raise_on_failure=>true, :timeout=>2.0)
=> [9545, 6623]
FastImage.new("http://stephensykes.com/images/pngimage").content_length
=> 432
FastImage.size("http://stephensykes.com/images/ss.com_x.gif", :http_header => {'User-Agent' => 'Fake Browser'})
=> [266, 56]
FastImage.new("http://stephensykes.com/images/ExifOrientation3.jpg").orientation
=> 3
FastImage.size("data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")
=> [1, 1]
h2. Installation
h4. Required Ruby version
FastImage version 2.0.0 and above work with Ruby 1.9.2 and above.
FastImage version 1.9.0 was the last version that supported Ruby 1.8.7.
h4. Gem
bc. gem install fastimage
h4. Rails
Add fastimage to your Gemfile, and bundle.
bc. gem 'fastimage'
Then you're off - just use @FastImage.size()@ and @FastImage.type()@ in your code as in the examples.
h2. Documentation
"http://sdsykes.github.io/fastimage/rdoc/FastImage.html":http://sdsykes.github.io/fastimage/rdoc/FastImage.html
h2. Maintainer
FastImage is maintained by Stephen Sykes (@sdsykes). Support this project by using "LibPixel":https://libpixel.com cloud based image resizing and processing service.
h2. Benchmark
It's way faster than conventional methods (for example the image_size gem) for most types of file when fetching over the wire.
irb> uri = "http://upload.wikimedia.org/wikipedia/commons/b/b4/Mardin_1350660_1350692_33_images.jpg"
irb> puts Benchmark.measure {open(uri, 'rb') {|fh| p ImageSize.new(fh).size}}
[9545, 6623]
0.680000 0.250000 0.930000 ( 7.571887)
irb> puts Benchmark.measure {p FastImage.size(uri)}
[9545, 6623]
0.010000 0.000000 0.010000 ( 0.090640)
The file is fetched in about 7.5 seconds in this test (the number in brackets is the total time taken), but as FastImage doesn't need to fetch the whole thing, it completes in less than 0.1s.
You'll see similar excellent results for the other file types, except for TIFF. Unfortunately TIFFs tend to have their
metadata towards the end of the file, so it makes little difference to do a minimal fetch. The result shown below is
mostly dependent on the exact internet conditions during the test, and little to do with the library used.
irb> uri = "http://upload.wikimedia.org/wikipedia/commons/1/11/Shinbutsureijoushuincho.tiff"
irb> puts Benchmark.measure {open(uri, 'rb') {|fh| p ImageSize.new(fh).size}}
[1120, 1559]
1.080000 0.370000 1.450000 ( 13.766962)
irb> puts Benchmark.measure {p FastImage.size(uri)}
[1120, 1559]
3.490000 3.810000 7.300000 ( 11.754315)
h2. Tests
You'll need to @gem install fakeweb@ and possibly also @gem install test-unit@ to be able to run the tests.
bc.. $ ruby test.rb
Run options:
# Running tests:
Finished tests in 1.033640s, 23.2189 tests/s, 82.2337 assertions/s.
24 tests, 85 assertions, 0 failures, 0 errors, 0 skips
h2. References
* "Pennysmalls - Find jpeg dimensions fast in pure Ruby, no image library needed":http://pennysmalls.wordpress.com/2008/08/19/find-jpeg-dimensions-fast-in-pure-ruby-no-ima/
* "Antti Kupila - Getting JPG dimensions with AS3 without loading the entire file":http://www.anttikupila.com/flash/getting-jpg-dimensions-with-as3-without-loading-the-entire-file/
* "imagesize gem":https://rubygems.org/gems/imagesize
* "EXIF Reader":https://github.com/remvee/exifr
h2. FastImage in other languages
* "Python by bmuller":https://github.com/bmuller/fastimage
* "Swift by kaishin":https://github.com/kaishin/ImageScout
* "Go by rubenfonseca":https://github.com/rubenfonseca/fastimage
* "PHP by tommoor":https://github.com/tommoor/fastimage
* "Node.js by ShogunPanda":https://github.com/ShogunPanda/fastimage
* "Objective C by kylehickinson":https://github.com/kylehickinson/FastImage
* "Android by qstumn":https://github.com/qstumn/FastImageSize
h2. Licence
MIT, see file "MIT-LICENSE":MIT-LICENSE
fastimage-2.1.7/Rakefile 0000664 0000000 0000000 00000000604 13534264000 0015123 0 ustar 00root root 0000000 0000000 require "rdoc/task"
require 'rake/testtask'
# Generate documentation
Rake::RDocTask.new do |rd|
rd.main = "README.rdoc"
rd.rdoc_files.include("*.rdoc", "lib/**/*.rb")
rd.rdoc_dir = "rdoc"
end
#require 'bundler'
#Bundler::GemHelper.install_tasks
Rake::TestTask.new do |t|
t.libs << "test"
t.test_files = FileList['test/test.rb']
t.verbose = true
end
task :default => :test
fastimage-2.1.7/fastimage.gemspec 0000664 0000000 0000000 00000001626 13534264000 0016770 0 ustar 00root root 0000000 0000000 Gem::Specification.new do |s|
s.name = %q{fastimage}
s.version = "2.1.7"
s.required_ruby_version = '>= 1.9.2'
s.authors = ["Stephen Sykes"]
s.date = %q{2019-09-05}
s.description = %q{FastImage finds the size or type of an image given its uri by fetching as little as needed.}
s.email = %q{sdsykes@gmail.com}
s.extra_rdoc_files = [
"README.textile"
]
s.files = [
"MIT-LICENSE",
"README.textile",
"lib/fastimage.rb",
]
s.homepage = %q{http://github.com/sdsykes/fastimage}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}
s.summary = %q{FastImage - Image info fast}
s.add_development_dependency 'fakeweb-fi', '~> 1.3'
# Note rake 11 drops support for ruby 1.9.2
s.add_development_dependency('rake', '~> 10.5')
s.add_development_dependency('rdoc')
s.add_development_dependency('test-unit')
s.licenses = ['MIT']
end
fastimage-2.1.7/lib/ 0000775 0000000 0000000 00000000000 13534264000 0014224 5 ustar 00root root 0000000 0000000 fastimage-2.1.7/lib/fastimage.rb 0000664 0000000 0000000 00000052562 13534264000 0016523 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
# coding: ASCII-8BIT
# FastImage finds the size or type of an image given its uri.
# It is careful to only fetch and parse as much of the image as is needed to determine the result.
# It does this by using a feature of Net::HTTP that yields strings from the resource being fetched
# as soon as the packets arrive.
#
# No external libraries such as ImageMagick are used here, this is a very lightweight solution to
# finding image information.
#
# FastImage knows about GIF, JPEG, BMP, TIFF, ICO, CUR, PNG, PSD, SVG and WEBP files.
#
# FastImage can also read files from the local filesystem by supplying the path instead of a uri.
# In this case FastImage reads the file in chunks of 256 bytes until
# it has enough. This is possibly a useful bandwidth-saving feature if the file is on a network
# attached disk rather than truly local.
#
# FastImage will automatically read from any object that responds to :read - for
# instance an IO object if that is passed instead of a URI.
#
# FastImage will follow up to 4 HTTP redirects to get the image.
#
# FastImage also provides a reader for the content length header provided in HTTP.
# This may be useful to assess the file size of an image, but do not rely on it exclusively -
# it will not be present in chunked responses for instance.
#
# FastImage accepts additional HTTP headers. This can be used to set a user agent
# or referrer which some servers require. Pass an :http_header argument to specify headers,
# e.g., :http_header => {'User-Agent' => 'Fake Browser'}.
#
# FastImage can give you information about the parsed display orientation of an image with Exif
# data (jpeg or tiff).
#
# === Examples
# require 'fastimage'
#
# FastImage.size("http://stephensykes.com/images/ss.com_x.gif")
# => [266, 56]
# FastImage.type("http://stephensykes.com/images/pngimage")
# => :png
# FastImage.type("/some/local/file.gif")
# => :gif
# File.open("/some/local/file.gif", "r") {|io| FastImage.type(io)}
# => :gif
# FastImage.new("http://stephensykes.com/images/pngimage").content_length
# => 432
# FastImage.new("http://stephensykes.com/images/ExifOrientation3.jpg").orientation
# => 3
#
# === References
# * http://www.anttikupila.com/flash/getting-jpg-dimensions-with-as3-without-loading-the-entire-file/
# * http://pennysmalls.wordpress.com/2008/08/19/find-jpeg-dimensions-fast-in-pure-ruby-no-ima/
# * https://rubygems.org/gems/imagesize
# * https://github.com/remvee/exifr
#
require 'net/https'
require 'delegate'
require 'pathname'
require 'zlib'
require 'base64'
require 'uri'
# see http://stackoverflow.com/questions/5208851/i/41048816#41048816
if RUBY_VERSION < "2.2"
module URI
DEFAULT_PARSER = Parser.new(:HOSTNAME => "(?:(?:[a-zA-Z\\d](?:[-\\_a-zA-Z\\d]*[a-zA-Z\\d])?)\\.)*(?:[a-zA-Z](?:[-\\_a-zA-Z\\d]*[a-zA-Z\\d])?)\\.?")
end
end
class FastImage
attr_reader :size, :type, :content_length, :orientation
attr_reader :bytes_read
class FastImageException < StandardError # :nodoc:
end
class UnknownImageType < FastImageException # :nodoc:
end
class ImageFetchFailure < FastImageException # :nodoc:
end
class SizeNotFound < FastImageException # :nodoc:
end
class CannotParseImage < FastImageException # :nodoc:
end
DefaultTimeout = 2 unless const_defined?(:DefaultTimeout)
LocalFileChunkSize = 256 unless const_defined?(:LocalFileChunkSize)
# Returns an array containing the width and height of the image.
# It will return nil if the image could not be fetched, or if the image type was not recognised.
#
# By default there is a timeout of 2 seconds for opening and reading from a remote server.
# This can be changed by passing a :timeout => number_of_seconds in the options.
#
# If you wish FastImage to raise if it cannot size the image for any reason, then pass
# :raise_on_failure => true in the options.
#
# FastImage knows about GIF, JPEG, BMP, TIFF, ICO, CUR, PNG, PSD, SVG and WEBP files.
#
# === Example
#
# require 'fastimage'
#
# FastImage.size("http://stephensykes.com/images/ss.com_x.gif")
# => [266, 56]
# FastImage.size("http://stephensykes.com/images/pngimage")
# => [16, 16]
# FastImage.size("http://farm4.static.flickr.com/3023/3047236863_9dce98b836.jpg")
# => [500, 375]
# FastImage.size("http://www-ece.rice.edu/~wakin/images/lena512.bmp")
# => [512, 512]
# FastImage.size("test/fixtures/test.jpg")
# => [882, 470]
# FastImage.size("http://pennysmalls.com/does_not_exist")
# => nil
# FastImage.size("http://pennysmalls.com/does_not_exist", :raise_on_failure=>true)
# => raises FastImage::ImageFetchFailure
# FastImage.size("http://stephensykes.com/favicon.ico", :raise_on_failure=>true)
# => [16, 16]
# FastImage.size("http://stephensykes.com/images/squareBlue.icns", :raise_on_failure=>true)
# => raises FastImage::UnknownImageType
# FastImage.size("http://stephensykes.com/favicon.ico", :raise_on_failure=>true, :timeout=>0.01)
# => raises FastImage::ImageFetchFailure
# FastImage.size("http://stephensykes.com/images/faulty.jpg", :raise_on_failure=>true)
# => raises FastImage::SizeNotFound
#
# === Supported options
# [:timeout]
# Overrides the default timeout of 2 seconds. Applies both to reading from and opening the http connection.
# [:raise_on_failure]
# If set to true causes an exception to be raised if the image size cannot be found for any reason.
#
def self.size(uri, options={})
new(uri, options).size
end
# Returns an symbol indicating the image type fetched from a uri.
# It will return nil if the image could not be fetched, or if the image type was not recognised.
#
# By default there is a timeout of 2 seconds for opening and reading from a remote server.
# This can be changed by passing a :timeout => number_of_seconds in the options.
#
# If you wish FastImage to raise if it cannot find the type of the image for any reason, then pass
# :raise_on_failure => true in the options.
#
# === Example
#
# require 'fastimage'
#
# FastImage.type("http://stephensykes.com/images/ss.com_x.gif")
# => :gif
# FastImage.type("http://stephensykes.com/images/pngimage")
# => :png
# FastImage.type("http://farm4.static.flickr.com/3023/3047236863_9dce98b836.jpg")
# => :jpeg
# FastImage.type("http://www-ece.rice.edu/~wakin/images/lena512.bmp")
# => :bmp
# FastImage.type("test/fixtures/test.jpg")
# => :jpeg
# FastImage.type("http://stephensykes.com/does_not_exist")
# => nil
# File.open("/some/local/file.gif", "r") {|io| FastImage.type(io)}
# => :gif
# FastImage.type("test/fixtures/test.tiff")
# => :tiff
# FastImage.type("test/fixtures/test.psd")
# => :psd
#
# === Supported options
# [:timeout]
# Overrides the default timeout of 2 seconds. Applies both to reading from and opening the http connection.
# [:raise_on_failure]
# If set to true causes an exception to be raised if the image type cannot be found for any reason.
#
def self.type(uri, options={})
new(uri, options.merge(:type_only=>true)).type
end
def initialize(uri, options={})
@uri = uri
@options = {
:type_only => false,
:timeout => DefaultTimeout,
:raise_on_failure => false,
:proxy => nil,
:http_header => {}
}.merge(options)
@property = @options[:type_only] ? :type : :size
@type, @state = nil
if uri.respond_to?(:read)
fetch_using_read(uri)
elsif uri.start_with?('data:')
fetch_using_base64(uri)
else
begin
@parsed_uri = URI.parse(uri)
rescue URI::InvalidURIError
fetch_using_file_open
else
if @parsed_uri.scheme == "http" || @parsed_uri.scheme == "https"
fetch_using_http
else
fetch_using_file_open
end
end
end
raise SizeNotFound if @options[:raise_on_failure] && @property == :size && !@size
rescue Timeout::Error, SocketError, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ECONNRESET,
Errno::ENETUNREACH, ImageFetchFailure, Net::HTTPBadResponse, EOFError, Errno::ENOENT,
OpenSSL::SSL::SSLError
raise ImageFetchFailure if @options[:raise_on_failure]
rescue NoMethodError # 1.8.7p248 can raise this due to a net/http bug
raise ImageFetchFailure if @options[:raise_on_failure]
rescue UnknownImageType
raise UnknownImageType if @options[:raise_on_failure]
rescue CannotParseImage
if @options[:raise_on_failure]
if @property == :size
raise SizeNotFound
else
raise ImageFetchFailure
end
end
ensure
uri.rewind if uri.respond_to?(:rewind)
end
private
def fetch_using_http
@redirect_count = 0
fetch_using_http_from_parsed_uri
end
# Some invalid locations need escaping
def escaped_location(location)
begin
URI(location)
rescue URI::InvalidURIError
URI.escape(location)
else
location
end
end
def fetch_using_http_from_parsed_uri
http_header = {'Accept-Encoding' => 'identity'}.merge(@options[:http_header])
setup_http
@http.request_get(@parsed_uri.request_uri, http_header) do |res|
if res.is_a?(Net::HTTPRedirection) && @redirect_count < 4
@redirect_count += 1
begin
@parsed_uri = URI.join(@parsed_uri, escaped_location(res['Location']))
rescue URI::InvalidURIError
else
fetch_using_http_from_parsed_uri
break
end
end
raise ImageFetchFailure unless res.is_a?(Net::HTTPSuccess)
@content_length = res.content_length
read_fiber = Fiber.new do
res.read_body do |str|
Fiber.yield str
end
end
case res['content-encoding']
when 'deflate', 'gzip', 'x-gzip'
begin
gzip = Zlib::GzipReader.new(FiberStream.new(read_fiber))
rescue FiberError, Zlib::GzipFile::Error
raise CannotParseImage
end
read_fiber = Fiber.new do
while data = gzip.readline
Fiber.yield data
end
end
end
parse_packets FiberStream.new(read_fiber)
break # needed to actively quit out of the fetch
end
end
def protocol_relative_url?(url)
url.start_with?("//")
end
def proxy_uri
begin
if @options[:proxy]
proxy = URI.parse(@options[:proxy])
else
proxy = ENV['http_proxy'] && ENV['http_proxy'] != "" ? URI.parse(ENV['http_proxy']) : nil
end
rescue URI::InvalidURIError
proxy = nil
end
proxy
end
def setup_http
proxy = proxy_uri
if proxy
@http = Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password).new(@parsed_uri.host, @parsed_uri.port)
else
@http = Net::HTTP.new(@parsed_uri.host, @parsed_uri.port)
end
@http.use_ssl = (@parsed_uri.scheme == "https")
@http.verify_mode = OpenSSL::SSL::VERIFY_NONE
@http.open_timeout = @options[:timeout]
@http.read_timeout = @options[:timeout]
end
def fetch_using_read(readable)
readable.rewind if readable.respond_to?(:rewind)
# Pathnames respond to read, but always return the first
# chunk of the file unlike an IO (even though the
# docuementation for it refers to IO). Need to supply
# an offset in this case.
if readable.is_a?(Pathname)
read_fiber = Fiber.new do
offset = 0
while str = readable.read(LocalFileChunkSize, offset)
Fiber.yield str
offset += LocalFileChunkSize
end
end
else
read_fiber = Fiber.new do
while str = readable.read(LocalFileChunkSize)
Fiber.yield str
end
end
end
parse_packets FiberStream.new(read_fiber)
end
def fetch_using_file_open
@content_length = File.size?(@uri)
File.open(@uri) do |s|
fetch_using_read(s)
end
end
def parse_packets(stream)
@stream = stream
begin
result = send("parse_#{@property}")
if result
# extract exif orientation if it was found
if @property == :size && result.size == 3
@orientation = result.pop
else
@orientation = 1
end
instance_variable_set("@#{@property}", result)
else
raise CannotParseImage
end
rescue FiberError
raise CannotParseImage
end
end
def parse_size
@type = parse_type unless @type
send("parse_size_for_#{@type}")
end
def fetch_using_base64(uri)
data = uri.split(',')[1]
decoded = Base64.decode64(data)
@content_length = decoded.size
fetch_using_read StringIO.new(decoded)
end
module StreamUtil # :nodoc:
def read_byte
read(1)[0].ord
end
def read_int
read(2).unpack('n')[0]
end
def read_string_int
value = []
while read(1) =~ /(\d)/
value << $1
end
value.join.to_i
end
end
class FiberStream # :nodoc:
include StreamUtil
attr_reader :pos
def initialize(read_fiber)
@read_fiber = read_fiber
@pos = 0
@strpos = 0
@str = ''
end
# Peeking beyond the end of the input will raise
def peek(n)
while @strpos + n - 1 >= @str.size
unused_str = @str[@strpos..-1]
new_string = @read_fiber.resume
raise CannotParseImage if !new_string
# we are dealing with bytes here, so force the encoding
new_string.force_encoding("ASCII-8BIT") if String.method_defined? :force_encoding
@str = unused_str + new_string
@strpos = 0
end
@str[@strpos..(@strpos + n - 1)]
end
def read(n)
result = peek(n)
@strpos += n
@pos += n
result
end
def skip(n)
discarded = 0
fetched = @str[@strpos..-1].size
while n > fetched
discarded += @str[@strpos..-1].size
new_string = @read_fiber.resume
raise CannotParseImage if !new_string
new_string.force_encoding("ASCII-8BIT") if String.method_defined? :force_encoding
fetched += new_string.size
@str = new_string
@strpos = 0
end
@strpos = @strpos + n - discarded
@pos += n
end
end
class IOStream < SimpleDelegator # :nodoc:
include StreamUtil
end
def parse_type
parsed_type = case @stream.peek(2)
when "BM"
:bmp
when "GI"
:gif
when 0xff.chr + 0xd8.chr
:jpeg
when 0x89.chr + "P"
:png
when "II", "MM"
case @stream.peek(11)[8..10]
when "APC", "CR\002"
nil # do not recognise CRW or CR2 as tiff
else
:tiff
end
when '8B'
:psd
when "\0\0"
# ico has either a 1 (for ico format) or 2 (for cursor) at offset 3
case @stream.peek(3).bytes.to_a.last
when 1 then :ico
when 2 then :cur
end
when "RI"
:webp if @stream.peek(12)[8..11] == "WEBP"
when "