/
fastimage.rb
893 lines (785 loc) · 24.2 KB
/
fastimage.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
294
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
# 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, :animated
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
# Returns an positive value indicating the image is animated.
# 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.animated?("test/fixtures/test.gif")
# => false
# FastImage.animated?("test/fixtures/animated.gif")
# => true
#
# === 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.animated?(uri, options={})
new(uri, options.merge(:animated_only=>true)).animated
end
def initialize(uri, options={})
@uri = uri
@options = {
:type_only => false,
:timeout => DefaultTimeout,
:raise_on_failure => false,
:proxy => nil,
:http_header => {}
}.merge(options)
@property = if @options[:animated_only]
:animated
elsif @options[:type_only]
:type
else
:size
end
@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 != nil
# 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 parse_animated
@type = parse_type unless @type
@type == :gif ? send("parse_animated_for_#{@type}") : nil
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 "<s"
:svg
when /<[?!]/
# Peek 10 more chars each time, and if end of file is reached just raise
# unknown. We assume the <svg tag cannot be within 10 chars of the end of
# the file, and is within the first 250 chars.
begin
:svg if (1..25).detect {|n| @stream.peek(10 * n).include?("<svg")}
rescue FiberError
nil
end
end
parsed_type or raise UnknownImageType
end
def parse_size_for_ico
icons = @stream.read(6)[4..5].unpack('v').first
sizes = icons.times.map { @stream.read(16).unpack('C2').map { |x| x == 0 ? 256 : x } }.sort_by { |w,h| w * h }
sizes.last
end
alias_method :parse_size_for_cur, :parse_size_for_ico
class Gif # :nodoc:
def initialize(stream)
@stream = stream
end
def width_and_height
@stream.read(11)[6..10].unpack('SS')
end
# Checks if a delay between frames exists and if it does, then the GIFs is
# animated
def animated?
delay = 0
@stream.read(10) # "GIF" + version (3) + width (2) + height (2)
fields = @stream.read(3).unpack("C")[0] # fields (1) + bg color (1) + pixel ratio (1)
# Skip Global Color Table if it exists
if fields & 0x80
# 2 * (depth + 1) colors, each occupying 3 bytes (RGB)
@stream.skip(3 * 2 ** ((fields & 0x7) + 1))
end
loop do
block_type = @stream.read(1).unpack("C")[0]
if block_type == 0x21
extension_type = @stream.read(1).unpack("C")[0]
size = @stream.read(1).unpack("C")[0]
if extension_type == 0xF9
delay = @stream.read(4).unpack("CSC")[1] # fields (1) + delay (2) + transparent index (1)
break
elsif extension_type == 0xFF
@stream.skip(size) # application ID (8) + version (3)
else
return # unrecognized extension
end
skip_sub_blocks
else
return # unrecognized block
end
end
delay > 0
end
private
def skip_sub_blocks
loop do
size = @stream.read(1).unpack("C")[0]
if size == 0
break
else
@stream.skip(size)
end
end
end
end
def parse_size_for_gif
gif = Gif.new(@stream)
gif.width_and_height
end
def parse_size_for_png
@stream.read(25)[16..24].unpack('NN')
end
def parse_size_for_jpeg
exif = nil
loop do
@state = case @state
when nil
@stream.skip(2)
:started
when :started
@stream.read_byte == 0xFF ? :sof : :started
when :sof
case @stream.read_byte
when 0xe1 # APP1
skip_chars = @stream.read_int - 2
data = @stream.read(skip_chars)
io = StringIO.new(data)
if io.read(4) == "Exif"
io.read(2)
new_exif = Exif.new(IOStream.new(io)) rescue nil
exif ||= new_exif # only use the first APP1 segment
end
:started
when 0xe0..0xef
:skipframe
when 0xC0..0xC3, 0xC5..0xC7, 0xC9..0xCB, 0xCD..0xCF
:readsize
when 0xFF
:sof
else
:skipframe
end
when :skipframe
skip_chars = @stream.read_int - 2
@stream.skip(skip_chars)
:started
when :readsize
@stream.skip(3)
height = @stream.read_int
width = @stream.read_int
width, height = height, width if exif && exif.rotated?
return [width, height, exif ? exif.orientation : 1]
end
end
end
def parse_size_for_bmp
d = @stream.read(32)[14..28]
header = d.unpack("C")[0]
result = if header == 12
d[4..8].unpack('SS')
else
d[4..-1].unpack('l<l<')
end
# ImageHeight is expressed in pixels. The absolute value is necessary because ImageHeight can be negative
[result.first, result.last.abs]
end
def parse_size_for_webp
vp8 = @stream.read(16)[12..15]
_len = @stream.read(4).unpack("V")
case vp8
when "VP8 "
parse_size_vp8
when "VP8L"
parse_size_vp8l
when "VP8X"
parse_size_vp8x
else
nil
end
end
def parse_size_vp8
w, h = @stream.read(10).unpack("@6vv")
[w & 0x3fff, h & 0x3fff]
end
def parse_size_vp8l
@stream.skip(1) # 0x2f
b1, b2, b3, b4 = @stream.read(4).bytes.to_a
[1 + (((b2 & 0x3f) << 8) | b1), 1 + (((b4 & 0xF) << 10) | (b3 << 2) | ((b2 & 0xC0) >> 6))]
end
def parse_size_vp8x
flags = @stream.read(4).unpack("C")[0]
b1, b2, b3, b4, b5, b6 = @stream.read(6).unpack("CCCCCC")
width, height = 1 + b1 + (b2 << 8) + (b3 << 16), 1 + b4 + (b5 << 8) + (b6 << 16)
if flags & 8 > 0 # exif
# parse exif for orientation
# TODO: find or create test images for this
end
return [width, height]
end
class Exif # :nodoc:
attr_reader :width, :height, :orientation
def initialize(stream)
@stream = stream
@width, @height, @orientation = nil
parse_exif
end
def rotated?
@orientation >= 5
end
private
def get_exif_byte_order
byte_order = @stream.read(2)
case byte_order
when 'II'
@short, @long = 'v', 'V'
when 'MM'
@short, @long = 'n', 'N'
else
raise CannotParseImage
end
end
def parse_exif_ifd
tag_count = @stream.read(2).unpack(@short)[0]
tag_count.downto(1) do
type = @stream.read(2).unpack(@short)[0]
@stream.read(6)
data = @stream.read(2).unpack(@short)[0]
case type
when 0x0100 # image width
@width = data
when 0x0101 # image height
@height = data
when 0x0112 # orientation
@orientation = data
end
if @width && @height && @orientation
return # no need to parse more
end
@stream.read(2)
end
end
def parse_exif
@start_byte = @stream.pos
get_exif_byte_order
@stream.read(2) # 42
offset = @stream.read(4).unpack(@long)[0]
if @stream.respond_to?(:skip)
@stream.skip(offset - 8)
else
@stream.read(offset - 8)
end
parse_exif_ifd
@orientation ||= 1
end
end
def parse_size_for_tiff
exif = Exif.new(@stream)
if exif.rotated?
[exif.height, exif.width, exif.orientation]
else
[exif.width, exif.height, exif.orientation]
end
end
def parse_size_for_psd
@stream.read(26).unpack("x14NN").reverse
end
class Svg # :nodoc:
def initialize(stream)
@stream = stream
@width, @height, @ratio, @viewbox_width, @viewbox_height = nil
parse_svg
end
def width_and_height
if @width && @height
[@width, @height]
elsif @width && @ratio
[@width, @width / @ratio]
elsif @height && @ratio
[@height * @ratio, @height]
elsif @viewbox_width && @viewbox_height
[@viewbox_width, @viewbox_height]
else
nil
end
end
private
def parse_svg
attr_name = []
state = nil
while (char = @stream.read(1)) && state != :stop do
case char
when "="
if attr_name.join =~ /width/i
@stream.read(1)
@width = @stream.read_string_int
return if @height
elsif attr_name.join =~ /height/i
@stream.read(1)
@height = @stream.read_string_int
return if @width
elsif attr_name.join =~ /viewbox/i
values = attr_value.split(/\s/)
if values[2].to_f > 0 && values[3].to_f > 0
@ratio = values[2].to_f / values[3].to_f
@viewbox_width = values[2].to_i
@viewbox_height = values[3].to_i
end
end
when /\w/
attr_name << char
when "<"
attr_name = [char]
when ">"
state = :stop if state == :started
else
state = :started if attr_name.join == "<svg"
attr_name.clear
end
end
end
def attr_value
@stream.read(1)
value = []
while @stream.read(1) =~ /([^"])/
value << $1
end
value.join
end
end
def parse_size_for_svg
svg = Svg.new(@stream)
svg.width_and_height
end
def parse_animated_for_gif
gif = Gif.new(@stream)
gif.animated?
end
end