Compare commits

...

222 Commits

Author SHA1 Message Date
Stephen Sykes
a992939223 Include all the new files in the gem 2025-01-03 16:28:50 +00:00
Stephen Sykes
cce874f025
Merge pull request #155 from sdsykes/feature-refactoring
Split and refactor code + fixes
2025-01-03 12:30:20 +02:00
Stephen Sykes
4c06b15fa8 Update changelog and version 2025-01-03 10:26:28 +00:00
Stephen Sykes
7f6a50c6a4 Use more backward compatible unpack 2025-01-03 10:05:02 +00:00
Stephen Sykes
ba61a28d14 Remove entirely base64 dependency 2025-01-03 10:00:17 +00:00
Stephen Sykes
729438e55b Remove the base64 version altogether for compat 2025-01-02 21:21:18 +00:00
Stephen Sykes
d69288b504 Reduce base64 version requirement to support earlier rubies 2025-01-02 21:03:19 +00:00
Stephen Sykes
b6720dfdf7
Merge pull request #157 from mataku/base64-gem-warning
Add base64 as a dependency explicitly for Ruby 3.4.0 support
2025-01-02 22:58:09 +02:00
Stephen Sykes
499865e47a Test on ruby 3.4 2025-01-02 20:45:43 +00:00
Stephen Sykes
cad7175e06 Handle tiff format with long dimension values, fixes #158 2025-01-02 20:25:48 +00:00
Stephen Sykes
a891d8f43a Raise error correctly on bad url scheme, fixes #156 2025-01-02 19:44:19 +00:00
Takuma Homma
2c8539d503
Add base64 as a dependency explicitly for Ruby 3.4.0 support
ref. https://www.ruby-lang.org/en/news/2023/12/25/ruby-3-3-0-released/
2024-11-07 15:07:17 +09:00
Stephen Sykes
e7d8111784 Update checkout step 2024-04-06 16:41:04 +03:00
Stephen Sykes
ae60942b73 Upgrade actions steps, add v3.3 2024-04-06 16:37:56 +03:00
Stephen Sykes
a5e4052dd5 Incorporate lazy property fetching 2024-04-06 15:52:46 +03:00
Stephen Sykes
b50c834fad Split and refactor 2024-04-01 21:20:53 +03:00
Stephen Sykes
054f563321 Update supported file list 2024-04-01 19:45:21 +03:00
Stephen Sykes
df84ad4c8d
Merge pull request #154 from sdsykes/feature-add-jxl-support
Add initial jxl support
2024-04-01 19:30:21 +03:00
Stephen Sykes
8d02ae8257 Update version and changelog 2024-04-01 19:23:55 +03:00
Stephen Sykes
d1b1936b1d Add initial jxl support 2024-04-01 16:12:27 +03:00
Stephen Sykes
8495352ffe
Merge pull request #153 from sdsykes/fix-net-reader-error
Ensure nil is returned from dead fibers, fixes #152
2024-03-28 20:25:54 +02:00
Stephen Sykes
36ac12790d Rails Unknown if we run out of chars in an xml 2024-03-28 20:16:38 +02:00
Stephen Sykes
7de7faf8a3 Ensure nil is returned from dead fibers 2024-03-28 19:53:58 +02:00
Stephen Sykes
7d86b403b0 Fix maintainer 2024-03-24 17:16:34 +02:00
Stephen Sykes
99ac7d6df1 Minor fix to readme 2024-03-24 17:11:20 +02:00
Stephen Sykes
c5f76d0de2 Updat docuementation. Fixes #151 2024-03-24 17:08:06 +02:00
Stephen Sykes
f832581881 Fix file names 2023-12-24 12:02:45 +02:00
Stephen Sykes
c763b215cf Release 2.3.0 2023-12-24 12:01:26 +02:00
Stephen Sykes
8994844702 Fix readme badges 2023-09-29 10:11:58 +03:00
Stephen Sykes
b730e6b470 Update URLs 2023-09-29 10:05:26 +03:00
Stephen Sykes
413bd34c00
Merge pull request #147 from sandstrom/master-1
Update README
2023-09-29 09:46:15 +03:00
Stephen Sykes
6266b26b87 Add test for meta after mdat for heic 2023-09-28 17:28:33 +03:00
Stephen Sykes
02d70df8c1
Merge pull request #145 from ClearlyClaire/fixes/HEIC-meta-after-mdat
Handle large-size ISO_BMFF boxes and meta-after-mdat
2023-09-28 17:25:31 +03:00
Stephen Sykes
1fcc6c89ea
Merge pull request #144 from c960657/animated-gif
Add animated? support for png images
2023-09-28 16:47:31 +03:00
Stephen Sykes
71469cb64f Fix missing stringio require 2023-09-28 16:19:19 +03:00
Stephen Sykes
edf9558114 Update test paths for working ones 2023-09-28 16:18:59 +03:00
Stephen Sykes
c69d230098 Fix workflow for older rubies 2023-09-28 15:21:10 +03:00
Stephen Sykes
d515546a1d
Merge pull request #142 from dokioco/large-svg-header
Handle SVG files that have extra cruft at the start
2023-09-28 15:13:00 +03:00
Stephen Sykes
23989af8f9
Merge pull request #146 from nishidayuya/fix_cve_2012_2027_test_data
Fix CVE-2012-2027 vulnerability on test data
2023-09-28 15:04:21 +03:00
sandstrom
1a249b9e6d
Rename to README.md 2023-08-24 14:43:39 +02:00
sandstrom
22bdc7ba06
Update README.textile 2023-08-24 14:41:56 +02:00
Yuya.Nishida
2d546f4520 run: git cococo docker run -it --rm -v ./test/fixtures:/data alpine:3.18.3 sh -eux -c 'apk add --no-cache imagemagick && convert /data/test2.tiff /tmp/fixed-test2.tiff && mv /tmp/fixed-test2.tiff /data/test2.tiff' 2023-08-10 11:58:42 +09:00
Claire
7c49d67439 Handle large-size ISO_BMFF boxes and meta-after-mdat
Fixes #140
2023-08-07 14:12:59 +02:00
Christian Schmidt
fb319cda6e unpack1 is not supported on Ruby < 2.4 2023-08-06 21:55:00 +02:00
Christian Schmidt
3fdd1767f5 Add parse_animated_for_png 2023-08-03 23:36:50 +02:00
Alan Harper
7056a4b6c9 Handle SVG files that have extra cruft at the start 2023-05-29 12:31:35 +10:00
Sam
81b5b7d3df
Merge pull request #141 from xfalcox/animated_for_webp_and_avif
FEATURE: Adds animated? support for webp and avif images
2023-05-24 08:47:57 +10:00
Rafael dos Santos Silva
419bafca36
Smaller animated webp fixture file 2023-05-23 11:08:53 -03:00
Rafael dos Santos Silva
cb336762af
Version bump 2023-05-22 17:30:49 -03:00
Rafael dos Santos Silva
5528ef98d4
FEATURE: Adds animated? support for webp and avif images 2023-05-22 17:26:20 -03:00
Sam
b65d75c8a3
Merge pull request #139 from sdsykes/fix/NoMethodError
Handle nil being passed as uri
2023-04-11 11:26:30 +10:00
Stephen Sykes
e5266ff249 Handle nil being passed as uri
Fixes #138
2023-04-07 09:52:23 +03:00
Stephen Sykes
f8d0b37e95
Merge pull request #137 from orien/github-actions
Use GitHub Actions for CI
2023-01-17 08:01:16 +01:00
Orien Madgwick
c295d5da98 Use GitHub Actions for CI 2023-01-16 22:36:55 +11:00
Sam Saffron
6478cd33ac
bump version to 2.2.6 2021-12-16 11:21:35 +11:00
Sam
abd8059bd9
Merge pull request #135 from stefanoverna/avif-format
Add support for AVIF format
2021-12-16 11:17:38 +11:00
Stefano Verna
1a3e525c1d Add support for AVIF format 2021-12-15 14:52:24 +01:00
Sam Saffron
a1131d15bb
Bump version and introduce version file 2021-08-10 12:57:31 +10:00
Sam
f6559105f1
Merge pull request #131 from stefanoverna/fix-heic-rotation-angle
Use irot box to get HEIC/HEIF rotation angle
2021-08-09 15:31:46 +10:00
Stefano Verna
6025bd8819 Use irot box to get HEIC/HEIF rotation angle 2021-08-06 15:56:06 +02:00
Sam Saffron
4bdc514249
Changelog and version bump
Add a CHANGELOG to track changed to the library (only covering changes from
2.2.3 for now)

Add bundle/gem_tasks to make publishing the gem easier

Bump version to 2.2.4
2021-06-02 16:39:46 +10:00
Stephen Sykes
f0ea7da025
Merge pull request #126 from jbrw/master
Identify SVG files that start with a BOM character
2021-04-19 08:54:01 +03:00
Jamie Wilson
5dd8301141
Identify SVG files that start with a BOM character 2021-04-13 18:07:59 -04:00
Stephen Sykes
31ea417d8e
Merge pull request #125 from stefanoverna/heic-format
Add support for HEIC format
2021-04-05 14:59:30 +01:00
Stefano Verna
50b1631ae9 Prefer if modifier to postfix or condition 2021-03-15 08:48:47 +01:00
Stefano Verna
cd3ee0a624 Compat: %i[] is not available on Ruby 1.9 2021-03-03 12:37:13 +01:00
Stefano Verna
f2efc8c6c9 Compat: #unpack1 is not available on older Ruby versions 2021-03-03 09:25:34 +01:00
Stefano Verna
9baee6d1b3 Add FastImage::SUPPORTED_IMAGE_TYPES
Returns all the image formats FastImage is capable to recognize
2021-03-02 16:41:11 +01:00
Stefano Verna
58dcc3072f HEIC/HEIF format detection 2021-03-02 15:07:12 +01:00
Stephen Sykes
9a1400ebcc Bump version 2021-02-28 17:08:39 +02:00
Stephen Sykes
e72139ae17
Merge pull request #124 from stefanoverna/pr_svg
Identify svg files that start with white spaces
2021-02-28 16:52:42 +02:00
Fabrizio Monti
fcf871e637 Identify svg files that start with white spaces 2021-02-16 10:26:31 +01:00
Stephen Sykes
a440798854 Bump patch version 2021-01-30 19:23:34 +02:00
Stephen Sykes
e8ad2254e8 Test with Ruby 3 2021-01-30 15:42:00 +02:00
Stephen Sykes
98dcf9e491 Ignore pesky ds store files 2021-01-30 15:40:35 +02:00
Stephen Sykes
fd3b5f2c4c
Merge pull request #123 from Nakilon/master
force_encoding was called on Net::ReadAdapter when url is webmocked
fixes #121
2021-01-30 13:02:48 +02:00
Stephen Sykes
ddf9f25cef
Merge pull request #122 from nbianca/fix_gif
Fix GIF global color table flag check
2021-01-30 13:01:45 +02:00
Victor Maslov
437318220b force_encoding was called on Net::ReadAdapter when url is webmocked 2021-01-30 12:41:27 +03:00
Bianca Nenciu
e4c35d951e
Add an animated GIF without a global color table 2021-01-27 22:03:06 +02:00
Bianca Nenciu
c78578c097
Fix GIF global color table flag check
Zero is a truthy value, which is a problem when checking flags.
2021-01-21 17:20:51 +02:00
Stephen Sykes
c183bb833d bump version 2020-12-23 09:49:32 +02:00
Stephen Sykes
cb3a8cbeeb
Merge pull request #120 from ky1vstar/master
Add reference to Dart package
2020-11-06 08:06:56 +02:00
Aleksandr Zhuhan
fcf1704595
Update README.textile 2020-11-04 14:49:06 +02:00
Stephen Sykes
c93903eb5c
Merge pull request #119 from nbianca/master
Use frames count instead of delay to check animated GIFs
2020-11-03 16:55:08 +02:00
Bianca Nenciu
f1628c1539
Use frames count instead of delay to check animated GIFs
There are GIFs with multiple frames and zero delay, but also GIFs with
a single frame and positive delay. The old algorithm failed for this
kind of images.
2020-11-02 20:25:15 +02:00
Stephen Sykes
e4c198a02c Bump version 2020-07-23 11:31:21 +03:00
Stephen Sykes
c57b07dc85
Merge pull request #117 from PikachuEXE/replace-deprecated-method-usage
Replace deprecated method usage
2020-07-23 11:23:04 +03:00
PikachuEXE
0d4dd4a7ed * Test with 2.7 too 2020-07-23 15:22:29 +08:00
PikachuEXE
172b674a40 * Replace URI.escape with ::URI::DEFAULT_PARSER.escape
Similar code change
https://github.com/mongodb/mongo-ruby-driver/pull/1614/files
2020-07-23 15:22:29 +08:00
Stephen Sykes
099c5e4233
Merge pull request #116 from PikachuEXE/fix-incorrect-redirect-response-handling
Fix handling of redirect response without Location header
2020-06-22 06:59:01 +03:00
PikachuEXE
45521bfd3e Fix handling of redirect response without Location header 2020-06-18 11:56:03 +08:00
Stephen Sykes
8386e11db4 Update url for large image to https 2020-06-14 12:02:16 +03:00
Stephen Sykes
b58af86658 Fix returning nil if image type not gif for animated 2020-06-14 11:54:55 +03:00
Stephen Sykes
967737b844
Merge pull request #114 from nbianca/master
Add API to check if a GIF is animated
2020-06-14 11:39:32 +03:00
Bianca Nenciu
df31108b00 Add check for animated GIFs 2020-06-12 15:00:26 +03:00
Stephen Sykes
41088a55b6 Revert rake requirement since we still support ruby 1.9.2 2020-06-02 22:54:59 +03:00
Stephen Sykes
2decef3e02
Merge pull request #115 from gschlager/master
Avoid detecting arbitrary XML as SVG
2020-06-02 22:40:36 +03:00
Stephen Sykes
12a7dc4268 Update rake 2020-06-02 22:38:22 +03:00
Gerhard Schlager
2e0436c58f Avoid detecting arbitrary XML as SVG 2020-05-26 16:53:50 +02:00
Stephen Sykes
bad902712c
Merge pull request #111 from aried3r/ar/travis_update
Update Ruby 1.9-2.6
2019-10-24 18:19:02 +03:00
Anton Rieder
0d7ef4a548
Update Ruby 1.9-2.6 2019-10-24 15:06:58 +02:00
Stephen Sykes
021e5d3eb3
Merge pull request #110 from aried3r/patch-2
Use SVG Travis CI badge
2019-10-23 16:22:06 +03:00
Anton Rieder
692a1058a0
Use SVG Travis CI badge 2019-10-23 14:50:04 +02:00
Stephen Sykes
d1e49be9fc Bump version again 2019-09-05 22:54:40 +03:00
Stephen Sykes
6c7cdcd475 Merge branch 'master' of github.com:sdsykes/fastimage 2019-09-05 22:51:40 +03:00
Stephen Sykes
f82c2b192e Bump version 2019-09-05 22:51:30 +03:00
Stephen Sykes
a86e02db9c
Merge pull request #109 from abcang/supports_various_bitmap_headers
Supports various bitmap headers
2019-09-05 11:35:32 +03:00
abcang
6f548c5509 Supports various bitmap headers 2019-09-05 14:43:11 +09:00
Stephen Sykes
18831de7de
Merge pull request #108 from razola/proxy-auth
Support proxies that require a username and password
2019-03-20 09:24:50 +02:00
Sebastian Razola
ddfb29998a
Support proxies that require a username and password 2019-03-19 18:35:14 +01:00
Stephen Sykes
0dcffe126e
Update ruby versions for travis 2019-03-16 09:09:46 +02:00
Stephen Sykes
2132a8f99d
Merge pull request #107 from yahorzhylinski/handler-netunreach-exception
Handle `Errno::ENETUNREACH` exception
2019-03-16 09:06:14 +02:00
Yahor Zhylinski
3c5971e5b4 Handle Errno::ENETUNREACH exception 2019-03-13 09:21:07 +03:00
Stephen Sykes
9cc77e6e4c Bump version 2018-11-29 13:38:12 +02:00
Stephen Sykes
2187189d72
Merge pull request #106 from hbda/master
Should work for io's that have been read
2018-11-29 13:33:49 +02:00
Dmitry Borisov
11ca295071 Should work for readed ios 2018-11-29 13:15:28 +03:00
Stephen Sykes
929b4b76c5 Add ruby 2.5.1 to travis setup 2018-09-10 07:08:58 +03:00
Stephen Sykes
d75d16e3c4 Bump version 2018-09-09 22:47:43 +03:00
Stephen Sykes
aa097226e8 Avoid detecting CR2 and CRW as tiff. Use own fakeweb. Fixes #104 2018-09-09 22:39:40 +03:00
Stephen Sykes
15bc4111c4 Only escape location in redirect if needed. Fixes #103 2018-05-08 22:12:16 +03:00
Stephen Sykes
c4ffaf827c Bump version 2018-05-01 14:47:48 +03:00
Stephen Sykes
a6222c47a5
Merge pull request #101 from Nakilon/master
unescaped space symbol in redirect caused URI::InvalidURIError
2018-05-01 14:45:51 +03:00
Stephen Sykes
283911c168 Bump version 2018-05-01 14:43:36 +03:00
Stephen Sykes
15f3e95b25 Only pay attention to first APP1 segment for orientation. Fixes #102 2018-05-01 14:39:10 +03:00
Victor Maslov
abccdd1365 unescaped space symbol in redirect caused URI::InvalidURIError 2018-04-25 22:48:36 +03:00
Stephen Sykes
c7cad12fa0
Merge pull request #99 from Nakilon/master
better redirect handling
2018-04-20 13:54:26 +03:00
Stephen Sykes
7bc37c590a
Merge pull request #100 from shinichinomura/rescue-ssl-error
Rescue OpenSSL::SSL::SSLError
2018-04-20 12:04:22 +03:00
Shinichi NOMURA
2da45b1ed9 Rescue OpenSSL::SSL::SSLError 2018-04-20 17:58:39 +09:00
Victor Maslov
1be9e5cd7a better redirect handling 2018-04-04 17:09:14 +03:00
Stephen Sykes
0d4fbcbf76 Bump version 2017-12-18 12:18:10 +02:00
Stephen Sykes
32b5ba5c4b Add fix for data uri content length 2017-12-18 12:16:57 +02:00
Stephen Sykes
0cef2a777c Fix content_length for data uris, add test 2017-12-18 12:14:26 +02:00
Stephen Sykes
35d365565f Fix underscore test to be hosted at github 2017-12-18 11:44:28 +02:00
Stephen Sykes
271fb5d646 Merge pull request #93 from discourse/master
add support for doctype in SVG
2017-08-07 20:21:06 +03:00
Régis Hanol
2b4b69d80e add support for doctype in SVG 2017-08-07 10:14:37 +02:00
Stephen Sykes
921ed9a580 Merge pull request #90 from gfx/frokzen_string_literal
add frozen_string_literal: true
2017-07-04 10:03:12 +03:00
FUJI Goro (gfx)
e46c41a507 add frozen_string_literal: true 2017-07-04 11:32:25 +09:00
Stephen Sykes
7c10a0d8f9 Merge pull request #89 from timcraft/patch-2
Remove rubygems require from test.rb
2017-06-20 09:53:58 +03:00
Tim Craft
ec1632b8ef Remove rubygems require from test.rb 2017-06-17 12:32:22 +01:00
Stephen Sykes
3ca1029b0f Add maintainer to readme. 2017-06-01 15:37:11 +03:00
Stephen Sykes
6d489e6f6a Merge pull request #86 from dcorrigan/interpreter-warnings
declare instance variables explicitly
2017-05-08 08:36:13 +03:00
dcorrigan
bb4e64a455 declare instance variables explicitly 2017-05-05 09:33:04 -04:00
Stephen Sykes
5362469484 Add Android version to links 2017-04-27 22:02:10 +03:00
Stephen Sykes
7c9ef44362 Bump version 2017-02-23 22:28:03 +02:00
Stephen Sykes
0adc60812c Use viewbox if width and height are not present in svg. Fixes #76 2017-02-23 21:35:14 +02:00
Stephen Sykes
406c2a5734 Remove fiber require - not needed after all 2017-02-22 23:50:09 +02:00
Stephen Sykes
bd150b54af Fix parsing for svg with longer preamble 2017-02-22 23:47:56 +02:00
Stephen Sykes
ab07d1fe21 Set content length for local files. Fixes #77 2017-02-22 22:59:30 +02:00
Stephen Sykes
c89f556204 Fix protocol relative redirects, make new URI object if needed 2017-02-22 19:28:35 +02:00
Stephen Sykes
955d77a7e9 Merge pull request #78 from dennyac/handle-protocol-relative-uls
Handle protocol relative urls
2017-02-22 18:54:34 +02:00
Stephen Sykes
f92c8afffd Merge pull request #75 from jschwindt/master
Data URIs scheme handling
2017-02-22 08:18:46 -08:00
Stephen Sykes
bc43e8b570 Fix missing end 2017-02-22 18:17:22 +02:00
Stephen Sykes
b8e0bd7afb Merge branch 'master' into master 2017-02-22 08:13:37 -08:00
Stephen Sykes
2daadda6fc Don't test on 1.9.2, travis problems related to rdoc 2017-02-22 17:56:11 +02:00
Stephen Sykes
31042836d4 Remove addressable, include patch for older ruby versions than 2.2 2017-02-22 17:41:55 +02:00
Denny Abraham Cheriyan
88e2098d65 Handle protocol relative urls 2017-02-12 15:55:32 -08:00
Juan Schwindt
dde7d6c533 Add Data Uri handling support in README 2016-12-27 21:59:02 -03:00
Juan Schwindt
cbc17cbf69 Add support for Data Uri Scheme 2016-12-27 21:48:23 -03:00
Stephen Sykes
e8aec702fa Bump patch version 2016-11-03 12:38:52 +02:00
Stephen Sykes
63924a2a00 Merge pull request #67 from R-eenignE/master
Enclose README code phrases in Textile code markup
2016-11-03 12:30:49 +02:00
Stephen Sykes
a0808275f8 Add test for invalid ico files 2016-11-03 12:29:20 +02:00
Stephen Sykes
b9453d7733 Merge pull request #73 from Bertg/patch-2
Improve parse_type UnknownImageType detection
2016-11-03 12:24:36 +02:00
Bert Goethals
13b0244968 Improve parse_type UnknownImageType detection
In case of 'ice' file type when neither 1 or 2 is found it should raise ```UnknownImageType``` but it didn't, probably due to the method not being 100% DRY.

This commit fixes both issues at once
2016-10-17 17:10:38 +02:00
Stephen Sykes
c99b127d1b Add skip mechanism, to not read skipped bytes into memory. Fixes #70 2016-06-07 10:49:40 +03:00
Stephen Sykes
87cc1e7bdb Merge pull request #68 from michieldewit/largest_icon
For ICO files, return the largest size (by number of pixels) rather than the size of the first icon
2016-04-24 20:10:29 +03:00
Michiel de Wit
2453c60d6e For ICO files, return the largest size (by number of pixels) rather than the size of the first icon 2016-04-18 21:08:26 +02:00
Anthony C. Vizza
49bf0c0625 Enclose README code phrases in Textile code markup
Originally, this update was to prevent Textile from changing single
quotes into directional quotes in a code snippet under the Features
header.

The snippet pertains to setting additional HTTP headers:

    :http_header => {'User-Agent' => 'Fake Browser'}

To maintain consistency, all code phrases found under the Features
header were wrapped in @ symbols.

A couple minor typos were also corrected.
2016-04-13 19:47:12 -05:00
Stephen Sykes
c5cf98f54e Remove strict addressable requirement. Fixes #65 2016-03-24 19:34:11 +02:00
Stephen Sykes
64b624c538 Downloads info image 2016-03-24 19:28:18 +02:00
Stephen Sykes
67d2368176 Drop dead link 2016-03-24 18:33:44 +02:00
Stephen Sykes
cc28a5b248 Use earlier version of rake to fix 1.9.2 test 2016-03-24 18:28:53 +02:00
Stephen Sykes
e54e1e0b23 Remove support for 1.8.7, bump major version 2016-03-24 18:12:48 +02:00
Stephen Sykes
e53d427455 Remove contributors section
Check github’s various tools to know contribs, I don’t want to maintain
the list.
2016-03-24 18:11:49 +02:00
Stephen Sykes
a8826239e8 Whitespace fix 2016-03-24 18:10:46 +02:00
Stephen Sykes
9ab057cb7a Merge pull request #66 from janko-m/always-rewind-io
Always rewind the given IO
2016-03-24 17:39:05 +02:00
Janko Marohnić
04d1030756 Always rewind the given IO
When an error occured when extracting dimensions, rewinding would be
skipped and the code would jump straight to "rescue" statements. We want
that the IO is always rewinded, even in case of errors.

Note that this doesn't affect the return value of the method, because
the return value of a method-level "ensure" is always ignored by Ruby.
2016-03-08 21:09:42 +07:00
Stephen Sykes
9c7ada1a41 Merge pull request #64 from aried3r/patch-1
Add Ruby 2.2.4, 2.3.0 to Travis. Update to 2.1.8.
2016-02-15 22:34:48 +02:00
Anton Rieder
fb051f6b2f Add Ruby 2.2.4, 2.3.0 to Travis. Update to 2.1.8.
Also use containerized builds for Travis CI.
2016-02-15 17:06:19 +01:00
Stephen Sykes
094a94d581 Rake wasn't broken, reverts prev commit. Travis has issues. 2016-02-15 15:22:45 +02:00
Stephen Sykes
670fd3f2e3 Rake 10.5 seems to be broken on 1.8.7 2016-02-14 00:45:08 +02:00
Stephen Sykes
717c15d776 Addressable 2.4.0 broke support for ruby 1.8.7 2016-02-14 00:22:59 +02:00
Stephen Sykes
5320815974 Update gemspec, remove tests from gem 2016-02-13 23:50:20 +02:00
Stephen Sykes
f3ee9eeace Adds orientation reader and tests 2016-02-13 23:47:11 +02:00
Stephen Sykes
d3982fa009 Bump patch version 2015-12-02 10:41:31 +02:00
Stephen Sykes
ca29078b07 Merge pull request #62 from jvenezia/master
raise UnknownImageType when file is non-svg xml
2015-12-02 10:30:14 +02:00
Jeremy Venezia
4c1905fd66 raise UnknownImageType when file is non-svg xml 2015-12-01 17:49:05 +01:00
Stephen Sykes
f77a2b80bb Add objC port, fixes #60 2015-11-27 12:21:23 +02:00
Stephen Sykes
5c64fc9d11 Add node version of fastimage to the readme 2015-11-16 14:59:43 +02:00
Stephen Sykes
4a83842950 Bump minor version 2015-11-13 11:07:48 +02:00
Stephen Sykes
3c0c290ac8 Fix grammar erros, add info about headers to rdoc 2015-11-13 11:07:29 +02:00
Stephen Sykes
05457f9e89 Merge pull request #58 from cassioscabral/patch-1
Update readme with snippet for adding Gem into Gemfile
2015-11-13 11:00:15 +02:00
Stephen Sykes
4c83a818a5 Merge pull request #57 from andfx/user-agent
Support additional HTTP headers
2015-11-13 10:59:07 +02:00
Cassio Cabral
b550bd5615 Update readme with snippet for adding Gem into Gemfile
It explicitly shows how to add the gem to the Gemfile.
2015-11-12 18:12:28 -03:00
andfx
ad567ff0da Support additional HTTP headers 2015-11-09 21:10:16 +01:00
Stephen Sykes
b7bc775f4f Bump gemspec 2015-05-12 14:43:12 +03:00
Stephen Sykes
308e20cf45 More doc, set content_length earlier 2015-05-12 14:40:53 +03:00
Stephen Sykes
e4a5412d87 Doc updates 2015-05-12 14:33:01 +03:00
Stephen Sykes
013cd81ddb Merge pull request #52 from lulalala/file_size
Add reader for request header content-length
2015-05-12 14:25:46 +03:00
Stephen Sykes
f27a0e5943 Merge pull request #50 from kikihakiem/master
Add support for SVG
2015-05-12 13:45:08 +03:00
lulalala
fe5b4d7f04 Add reader for request header content-length 2015-05-11 20:05:14 +08:00
Kiki Luqman Hakiem
035ebe3ed6 Add read_string_int method to StreamUtil 2015-04-30 21:45:46 +07:00
Kiki Luqman Hakiem
39d9dfbf05 Handle partial viewport attribute 2015-04-26 03:14:04 +07:00
Kiki Luqman Hakiem
605bdc9452 Add support for SVG 2015-04-25 03:47:28 +07:00
Stephen Sykes
88355932a9 Adds link to PHP version 2015-03-19 20:20:54 +02:00
Stephen Sykes
3b84f548b1 v1.6.8 2015-03-05 21:27:06 +02:00
Stephen Sykes
36464d3bbc Use old syntax so old rubies can pass tests 2015-03-05 21:23:40 +02:00
Stephen Sykes
1511585281 Doc proxy argument 2015-03-05 21:21:20 +02:00
Stephen Sykes
4c20f466bb Merge branch 'forresty-proxy-option' 2015-03-05 21:14:19 +02:00
Stephen Sykes
034f5446df Remove Gemfile.lock from repo 2015-03-05 21:13:56 +02:00
Forrest Ye
5ebae8ea3b add options[:proxy] as a per request proxy config 2015-03-04 15:35:34 +08:00
Forrest Ye
01af8e520e clean up whitespace in test.rb 2015-03-04 15:31:11 +08:00
Forrest Ye
7547404945 add test-unit gem as dev dependency 2015-03-04 15:30:45 +08:00
Forrest Ye
8f9a740367 clean up whitespace 2015-03-04 15:21:32 +08:00
Stephen Sykes
1c1eb99395 Fix Gemfile.lock for v1.6.7 2015-03-01 08:55:38 +02:00
Stephen Sykes
a63c1d34d4 Merge branch 'master' of github.com:sdsykes/fastimage 2015-02-28 23:25:48 +02:00
Stephen Sykes
617449d4b5 Stop using openuri to open non http strings 2015-02-28 23:25:31 +02:00
Stephen Sykes
eb2ee31cd2 Merge pull request #43 from whistlerbrk/master
Silence already initialized constant warnings for apps/environments with...
2015-01-10 14:34:10 +02:00
Kunal Shah
d05ea84b5d Silence already initialized constant warnings for apps/environments with live reloads 2015-01-09 00:23:06 -05:00
Stephen Sykes
82d3525f40 Documentation updates 2015-01-07 12:15:28 +02:00
Stephen Sykes
ea0c36abea Adds webp support 2015-01-06 22:00:28 +02:00
Stephen Sykes
433c891313 Adds require zlib so old rubies work 2014-12-05 14:41:21 +02:00
Stephen Sykes
e4f700e539 fix gemfile.lock version 2014-12-05 14:28:04 +02:00
138 changed files with 2045 additions and 797 deletions

45
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,45 @@
---
name: Tests
on: [ push, pull_request ]
jobs:
test:
name: Test (Ruby ${{ matrix.ruby }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
ruby:
- '2.3'
- '2.4'
- '2.5'
- '2.6'
- '2.7'
- '3.0'
- '3.1'
- '3.2'
- '3.3'
- '3.4'
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- run: bundle exec rake
test_old_ruby:
name: Test (Ruby ${{ matrix.ruby }})
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
ruby:
- '2.0'
- '2.1'
- '2.2'
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- run: bundle exec rake

2
.gitignore vendored
View File

@ -1 +1,3 @@
pkg/
Gemfile.lock
.DS_Store

View File

@ -1,9 +0,0 @@
language: ruby
rvm:
- 1.8.7
- 1.9.2
- 1.9.3
- 2.0.0
- 2.1.2
# uncomment this line if your project needs to run something other than `rake`:
# script: bundle exec rspec spec

48
CHANGELOG Normal file
View File

@ -0,0 +1,48 @@
Version 2.4.0
03-Jan-2025
- IMPROVED: Refactor code into multiple files
- FIX: error rising from redirects to unknown url scheme
- FIX: Handle tiff format with long dimensions values
- FIX: Remove problematic dependency on base64 gem
- IMPROVED: properties including content_length are fetched more lazily improving performance
Version 2.3.1
01-Apr-2024
- FIX: avoid bug where a NoMethodError exception is raised on faulty images
Version 2.3.0
24-Dec-2023
- FIX: replace test tiff that triggers Clam-AV
- FIX: certain heif files could not be parsed
- FEATURE: Adds animated support for png
Version 2.2.7
23-May-2023
- FEATURE: Adds animated? support for webp and avif images
Version 2.2.6
16-December-2021
- FEATURE: Add support for AVIF support
Version 2.2.5
10-August-2021
- FIX: handle HEIC/HEIF rotation angle
Version 2.2.4
02-June-2021
- FEATURE: Added support for HEIC format
- FIX: Support SVG files that start with a BOM character

View File

@ -1,24 +0,0 @@
PATH
remote: .
specs:
fastimage (1.6.4)
addressable (~> 2.3, >= 2.3.5)
GEM
remote: https://rubygems.org/
specs:
addressable (2.3.6)
fakeweb (1.3.0)
json (1.8.1)
rake (10.3.1)
rdoc (4.1.1)
json (~> 1.4)
PLATFORMS
ruby
DEPENDENCIES
fakeweb (~> 1.3)
fastimage!
rake
rdoc

205
README.md Normal file
View File

@ -0,0 +1,205 @@
[![https://rubygems.org/gems/fastimage](https://img.shields.io/gem/dt/fastimage.svg)](https://rubygems.org/gems/fastimage)
[![https://github.com/sdsykes/fastimage/actions/workflows/test.yml](https://github.com/sdsykes/fastimage/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/sdsykes/fastimage/actions/workflows/test.yml)
# FastImage
**FastImage finds the size or type of an image given its uri by fetching as little as needed**
## 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, WEBP and JXL. 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.
## Features
- Reads local (and other) files - anything that is not parseable as a URI will be interpreted as a filename, and - will attempt to open it with `File#open`.
- Automatically reads from any object that responds to `:read` - for instance an IO object if that is passed instead of a URI.
- Follows up to 4 HTTP redirects to get the image.
- 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.
- Add a timeout to the request which will limit the request time by passing `:timeout => number_of_seconds`.
- Returns `nil` if it encounters an error, but you can pass `:raise_on_failure => true` to get an exception.
- 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.
- 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'}`.
- Gives you information about the parsed display orientation of an image with Exif data (jpeg or tiff).
- Handles [Data URIs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) correctly.
## Security
Take care to sanitise the strings passed to FastImage; it will try to read from whatever is passed.
## Examples
```ruby
require 'fastimage'
FastImage.size("https://switchstep.com/images/ios.gif")
=> [196, 283] # width, height
FastImage.type("http://switchstep.com/images/ss_logo.png")
=> :png
FastImage.type("/some/local/file.gif")
=> :gif
File.open("/some/local/file.gif", "r") {|io| FastImage.type(io)}
=> :gif
FastImage.size("http://switchstep.com/images/favicon.ico", :raise_on_failure=>true, :timeout=>0.01)
=> raises FastImage::ImageFetchFailure
FastImage.size("http://switchstep.com/images/favicon.ico", :raise_on_failure=>true, :timeout=>2)
=> [16, 16]
FastImage.size("http://switchstep.com/images/faulty.jpg", :raise_on_failure=>true)
=> raises FastImage::SizeNotFound
FastImage.new("http://switchstep.com/images/ss_logo.png").content_length
=> 4679
FastImage.size("http://switchstep.com/images/ss_logo.png", :http_header => {'User-Agent' => 'Fake Browser'})
=> [300, 300]
FastImage.new("http://switchstep.com/images/ExifOrientation3.jpg").orientation
=> 3
FastImage.size("data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")
=> [1, 1]
```
## Installation
### Gem
```sh
gem install fastimage
```
### Bundler
Add fastimage to your Gemfile.
```ruby
gem 'fastimage'
```
Then you're off - just use `FastImage.size()` and `FastImage.type()` in your code as in the examples.
## Documentation
http://sdsykes.github.io/fastimage/rdoc/FastImage.html
## Maintainer
FastImage is maintained by Stephen Sykes (sdsykes). SamSaffron also helps out from time to time (thanks!).
## Benchmark
It's way faster than conventional methods for most types of file when fetching over the wire. Compared here by using OpenURI which will fetch the whole file.
```ruby
require 'benchmark'
require 'fastimage'
require 'open-uri'
uri = "http://upload.wikimedia.org/wikipedia/commons/b/b4/Mardin_1350660_1350692_33_images.jpg"
puts Benchmark.measure {URI.open(uri, 'rb') {|fh| p FastImage.size(fh)}}
[9545, 6623]
0.059088 0.067694 0.126782 ( 0.808131)
puts Benchmark.measure {p FastImage.size(uri)}
[9545, 6623]
0.006198 0.001563 0.007761 ( 0.162021)
```
The file is fetched in about 0.8 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 0.16s.
You'll see similar excellent results for the other file types.
```ruby
require 'benchmark'
require 'fastimage'
require 'open-uri'
uri = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Augustine_Herrman_1670_Map_Virginia_Maryland.tiff"
puts Benchmark.measure {URI.open(uri, 'rb') {|fh| p FastImage.size(fh)}}
[12805, 10204]
1.332587 2.049915 3.382502 ( 19.925270)
puts Benchmark.measure {p FastImage.size(uri)}
[12805, 10204]
0.004593 0.000924 0.005517 ( 0.100592)
```
Some tiff files however do not have their metadata near the start of the file.
```ruby
require 'benchmark'
require 'fastimage'
require 'open-uri'
uri = "https://upload.wikimedia.org/wikipedia/commons/1/14/Center-Filled_LIMA.tif"
puts Benchmark.measure {URI.open(uri, 'rb') {|fh| p FastImage.size(fh)}}
[22841, 19404]
0.350304 0.321104 0.671408 ( 3.053605)
puts Benchmark.measure {p FastImage.size(uri)}
[22841, 19404]
0.163443 0.214301 0.377744 ( 2.880414)
```
Note that if you want a really fast result for this file type, [image_size](https://github.com/toy/image_size?tab=readme-ov-file#experimental-fetch-image-meta-from-http-server) might be useful as it has an optimisation for this (fetching only the needed data range).
```ruby
require 'benchmark'
require 'image_size/uri'
require 'fastimage'
uri = "https://upload.wikimedia.org/wikipedia/commons/1/14/Center-Filled_LIMA.tif"
puts Benchmark.measure {p ImageSize.url(uri).size }
[22841, 19404]
0.008983 0.001311 0.010294 ( 0.128986)
puts Benchmark.measure {p FastImage.size(uri)}
[22841, 19404]
0.163443 0.214301 0.377744 ( 2.880414)
```
## Tests
You'll need to bundle, or `gem install fakeweb` and possibly also `gem install test-unit` to be able to run the tests.
```sh
ruby test/test.rb
```
## 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](https://www.anttikupila.com/archive/getting-jpg-dimensions/)
- [imagesize gem](https://rubygems.org/gems/imagesize)
- [EXIF Reader](https://github.com/remvee/exifr)
## 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)
- [Flutter by ky1vstar](https://github.com/ky1vstar/fastimage.dart)
### Also of interest
- [C++ by xiaozhuai](https://github.com/xiaozhuai/imageinfo)
- [Rust by xiaozhuai](https://github.com/xiaozhuai/imageinfo-rs)
## Licence
MIT, see file "MIT-LICENSE"

View File

@ -1,134 +0,0 @@
!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 and PSD. 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, and uses the Addressable library to do so.
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 will obey the http_proxy setting in your environment to route requests via a proxy.
You can add a timeout to the request which will limit the request time by passing :timeout => number_of_seconds.
FastImage normally replies will nil if it encounters an error, but you can pass :raise_on_failure => true to get an exception.
h2. Examples
<pre lang="ruby"><code>
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]
</code></pre>
h2. Installation
h4. Gem
bc. gem install fastimage
h4. Rails
Add fastimage to your Gemfile, and bundle.
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. Benchmark
It's way faster than conventional methods (for example the image_size gem) for most types of file when fetching over the wire.
<pre lang="ruby"><code>
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)
</code></pre>
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.
<pre lang="ruby"><code>
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)
</code></pre>
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/
* "DZone - Determine Image Size":http://snippets.dzone.com/posts/show/805
* "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 documentation":http://imagesize.rubyforge.org/
* "EXIF Reader":https://github.com/remvee/exifr
h2. Licence
MIT, see file "MIT-LICENSE":MIT-LICENSE
h2. Contributors
Pull requests and suggestions are always welcome. Thanks to all the contributors!
* @felixbuenemann
* @speedmax
* @sebastianludwig
* @benjaminjackson
* @muffinista
* @marcandre
* @apanzerj

View File

@ -1,5 +1,8 @@
# frozen_string_literal: true
require "rdoc/task"
require 'rake/testtask'
require "rake/testtask"
require "bundler/gem_tasks"
# Generate documentation
Rake::RDocTask.new do |rd|

View File

@ -1,55 +1,30 @@
require_relative "lib/fastimage/version"
Gem::Specification.new do |s|
s.name = %q{fastimage}
s.version = "1.6.5"
s.version = FastImage::VERSION
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.required_ruby_version = '>= 1.9.2'
s.authors = ["Stephen Sykes"]
s.date = %q{2014-12-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"
"README.md"
]
s.files = [
"MIT-LICENSE",
"README.textile",
"lib/fastimage.rb",
"lib/fastimage/fbr.rb",
"test/fixtures/faulty.jpg",
"test/fixtures/test.bmp",
"test/fixtures/test2.bmp",
"test/fixtures/test.gif",
"test/fixtures/test.jpg",
"test/fixtures/test.png",
"test/fixtures/test2.jpg",
"test/fixtures/test3.jpg",
"test/fixtures/test4.jpg",
"test/fixtures/test.tiff",
"test/fixtures/test2.tiff",
"test/fixtures/exif_orientation.jpg",
"test/fixtures/infinite.jpg",
"test/fixtures/orient_2.jpg",
"test/fixtures/folder with spaces/test.bmp",
"test/test.rb",
"test/fixtures/test.psd",
"test/fixtures/bad.jpg",
"test/fixtures/man.ico",
"test/fixtures/test.cur",
"test/fixtures/gzipped.jpg",
"test/fixtures/truncated_gzipped.jpg"
]
"README.md"
] + Dir.glob("lib/**/*")
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_runtime_dependency 'addressable', '~> 2.3', '>= 2.3.5'
s.add_development_dependency 'fakeweb', '~> 1.3'
s.add_development_dependency('rake')
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.test_files = [
"test/test.rb"
]
s.licenses = ['MIT']
end

View File

@ -1,3 +1,4 @@
# frozen_string_literal: true
# coding: ASCII-8BIT
# FastImage finds the size or type of an image given its uri.
@ -8,10 +9,10 @@
# 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 and PSD files.
# FastImage knows about GIF, JPEG, BMP, TIFF, ICO, CUR, PNG, HEIC/HEIF, AVIF, PSD, SVG, WEBP and JXL files.
#
# FastImage can also read files from the local filesystem by supplying the path instead of a uri.
# In this case FastImage uses the Addressable library to read the file in chunks of 256 bytes until
# 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.
#
@ -20,529 +21,53 @@
#
# 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")
# FastImage.size("https://switchstep.com/images/ios.gif")
# => [196, 283]
# FastImage.type("http://switchstep.com/images/ss_logo.png")
# => :png
# FastImage.type("/some/local/file.gif")
# => :gif
# File.open("/some/local/file.gif", "r") {|io| FastImage.type(io)}
# => :gif
# FastImage.new("http://switchstep.com/images/ss_logo.png").content_length
# => 4679
# FastImage.new("http://switchstep.com/images/ExifOrientation3.jpg").orientation
# => 3
#
# === References
# * http://snippets.dzone.com/posts/show/805
# * 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/
# * http://imagesize.rubyforge.org/
# * https://rubygems.org/gems/imagesize
# * https://github.com/remvee/exifr
#
require 'net/https'
require 'addressable/uri'
require 'fastimage/fbr.rb'
require 'delegate'
require 'pathname'
require 'zlib'
require 'uri'
require 'stringio'
class FastImage
attr_reader :size, :type
require_relative 'fastimage/fastimage'
require_relative 'fastimage/version'
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
LocalFileChunkSize = 256
# 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, PNG, PSD, ICO and CUR 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={})
@property = options[:type_only] ? :type : :size
@timeout = options[:timeout] || DefaultTimeout
@uri = uri
if uri.respond_to?(:read)
fetch_using_read(uri)
else
begin
@parsed_uri = Addressable::URI.parse(uri)
rescue Addressable::URI::InvalidURIError
fetch_using_open_uri
else
if @parsed_uri.scheme == "http" || @parsed_uri.scheme == "https"
fetch_using_http
else
fetch_using_open_uri
end
end
end
uri.rewind if uri.respond_to?(:rewind)
raise SizeNotFound if options[:raise_on_failure] && @property == :size && !@size
rescue Timeout::Error, SocketError, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ECONNRESET,
ImageFetchFailure, Net::HTTPBadResponse, EOFError, Errno::ENOENT
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
end
private
def fetch_using_http
@redirect_count = 0
fetch_using_http_from_parsed_uri
end
def fetch_using_http_from_parsed_uri
setup_http
@http.request_get(@parsed_uri.request_uri, 'Accept-Encoding' => 'identity') do |res|
if res.is_a?(Net::HTTPRedirection) && @redirect_count < 4
@redirect_count += 1
begin
newly_parsed_uri = Addressable::URI.parse(res['Location'])
# The new location may be relative - check for that
if newly_parsed_uri.scheme != "http" && newly_parsed_uri.scheme != "https"
@parsed_uri.path = res['Location']
else
@parsed_uri = newly_parsed_uri
end
rescue Addressable::URI::InvalidURIError
else
fetch_using_http_from_parsed_uri
break
end
end
raise ImageFetchFailure unless res.is_a?(Net::HTTPSuccess)
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 proxy_uri
begin
proxy = ENV['http_proxy'] && ENV['http_proxy'] != "" ? Addressable::URI.parse(ENV['http_proxy']) : nil
rescue Addressable::URI::InvalidURIError
proxy = nil
end
proxy
end
def setup_http
proxy = proxy_uri
if proxy
@http = Net::HTTP::Proxy(proxy.host, proxy.port).new(@parsed_uri.host, @parsed_uri.inferred_port)
else
@http = Net::HTTP.new(@parsed_uri.host, @parsed_uri.inferred_port)
end
@http.use_ssl = (@parsed_uri.scheme == "https")
@http.verify_mode = OpenSSL::SSL::VERIFY_NONE
@http.open_timeout = @timeout
@http.read_timeout = @timeout
end
def fetch_using_read(readable)
# 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_open_uri
open(@uri) do |s|
fetch_using_read(s)
end
end
def parse_packets(stream)
@stream = stream
begin
result = send("parse_#{@property}")
if result
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
module StreamUtil # :nodoc:
def read_byte
read(1)[0].ord
end
def read_int
read(2).unpack('n')[0]
end
end
class FiberStream # :nodoc:
include StreamUtil
attr_reader :pos
def initialize(read_fiber)
@read_fiber = read_fiber
@pos = 0
@strpos = 0
@str = ''
end
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
result = @str[@strpos..(@strpos + n - 1)]
end
def read(n)
result = peek(n)
@strpos += n
@pos += n
result
end
end
class IOStream < SimpleDelegator # :nodoc:
include StreamUtil
end
def parse_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"
:tiff
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
else
raise UnknownImageType
end
end
def parse_size_for_ico
@stream.read(8)[6..7].unpack('CC').map{|byte| byte == 0 ? 256 : byte }
end
alias_method :parse_size_for_cur, :parse_size_for_ico
def parse_size_for_gif
@stream.read(11)[6..10].unpack('SS')
end
def parse_size_for_png
@stream.read(25)[16..24].unpack('NN')
end
def parse_size_for_jpeg
loop do
@state = case @state
when nil
@stream.read(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)
@exif = Exif.new(IOStream.new(io)) rescue nil
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.read(skip_chars)
:started
when :readsize
s = @stream.read(3)
height = @stream.read_int
width = @stream.read_int
width, height = height, width if @exif && @exif.rotated?
return [width, height]
end
end
end
def parse_size_for_bmp
d = @stream.read(32)[14..28]
header = d.unpack("C")[0]
result = if header == 40
d[4..-1].unpack('l<l<')
else
d[4..8].unpack('SS')
end
# ImageHeight is expressed in pixels. The absolute value is necessary because ImageHeight can be negative
[result.first, result.last.abs]
end
class Exif # :nodoc:
attr_reader :width, :height
def initialize(stream)
@stream = stream
parse_exif
end
def rotated?
@orientation && @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]
@stream.read(offset - 8)
parse_exif_ifd
end
end
def parse_size_for_tiff
exif = Exif.new(@stream)
if exif.rotated?
[exif.height, exif.width]
else
[exif.width, exif.height]
end
end
def parse_size_for_psd
@stream.read(26).unpack("x14NN").reverse
# 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

471
lib/fastimage/fastimage.rb Normal file
View File

@ -0,0 +1,471 @@
require_relative 'fastimage_parsing/image_base'
require_relative 'fastimage_parsing/stream_util'
require_relative 'fastimage_parsing/avif'
require_relative 'fastimage_parsing/bmp'
require_relative 'fastimage_parsing/exif'
require_relative 'fastimage_parsing/fiber_stream'
require_relative 'fastimage_parsing/gif'
require_relative 'fastimage_parsing/heic'
require_relative 'fastimage_parsing/ico'
require_relative 'fastimage_parsing/iso_bmff'
require_relative 'fastimage_parsing/jpeg'
require_relative 'fastimage_parsing/jxl'
require_relative 'fastimage_parsing/jxlc'
require_relative 'fastimage_parsing/png'
require_relative 'fastimage_parsing/psd'
require_relative 'fastimage_parsing/svg'
require_relative 'fastimage_parsing/tiff'
require_relative 'fastimage_parsing/type_parser'
require_relative 'fastimage_parsing/webp'
class FastImage
include FastImageParsing
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
class BadImageURI < FastImageException # :nodoc:
end
DefaultTimeout = 2 unless const_defined?(:DefaultTimeout)
LocalFileChunkSize = 256 unless const_defined?(:LocalFileChunkSize)
private
Parsers = {
:bmp => Bmp,
:gif => Gif,
:jpeg => Jpeg,
:png => Png,
:tiff => Tiff,
:psd => Psd,
:heic => Heic,
:heif => Heic,
:webp => Webp,
:svg => Svg,
:ico => Ico,
:cur => Ico,
:jxl => Jxl,
:avif => Avif
}.freeze
public
SUPPORTED_IMAGE_TYPES = Parsers.keys.freeze
# 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, HEIC/HEIF, AVIF, PSD, SVG, WEBP and JXL files.
#
# === Example
#
# require 'fastimage'
#
# FastImage.size("https://switchstep.com/images/ios.gif")
# => [196, 283]
# FastImage.size("http://switchstep.com/images/ss_logo.png")
# => [300, 300]
# FastImage.size("https://upload.wikimedia.org/wikipedia/commons/0/09/Jpeg_thumb_artifacts_test.jpg")
# => [1280, 800]
# FastImage.size("https://eeweb.engineering.nyu.edu/~yao/EL5123/image/lena_gray.bmp")
# => [512, 512]
# FastImage.size("test/fixtures/test.jpg")
# => [882, 470]
# FastImage.size("http://switchstep.com/does_not_exist")
# => nil
# FastImage.size("http://switchstep.com/does_not_exist", :raise_on_failure=>true)
# => raises FastImage::ImageFetchFailure
# FastImage.size("http://switchstep.com/images/favicon.ico", :raise_on_failure=>true)
# => [16, 16]
# FastImage.size("http://switchstep.com/foo.ics", :raise_on_failure=>true)
# => raises FastImage::UnknownImageType
# FastImage.size("http://switchstep.com/images/favicon.ico", :raise_on_failure=>true, :timeout=>0.01)
# => raises FastImage::ImageFetchFailure
# FastImage.size("http://switchstep.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("https://switchstep.com/images/ios.gif")
# => :gif
# FastImage.type("http://switchstep.com/images/ss_logo.png")
# => :png
# FastImage.type("https://upload.wikimedia.org/wikipedia/commons/0/09/Jpeg_thumb_artifacts_test.jpg")
# => :jpeg
# FastImage.type("https://eeweb.engineering.nyu.edu/~yao/EL5123/image/lena_gray.bmp")
# => :bmp
# FastImage.type("test/fixtures/test.jpg")
# => :jpeg
# FastImage.type("http://switchstep.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).type
end
# Returns a boolean 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).animated
end
def initialize(uri, options={})
@uri = uri
@options = {
:timeout => DefaultTimeout,
:raise_on_failure => false,
:proxy => nil,
:http_header => {}
}.merge(options)
end
def type
@property = :type
fetch unless defined?(@type)
@type
end
def size
@property = :size
begin
fetch unless defined?(@size)
rescue CannotParseImage
end
raise SizeNotFound if @options[:raise_on_failure] && !@size
@size
end
def orientation
size unless defined?(@size)
@orientation ||= 1 if @size
end
def width
size && @size[0]
end
def height
size && @size[1]
end
def animated
@property = :animated
fetch unless defined?(@animated)
@animated
end
def content_length
@property = :content_length
fetch unless defined?(@content_length)
@content_length
end
# find an appropriate method to fetch the image according to the passed parameter
def fetch
raise BadImageURI if @uri.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 UnknownImageType, BadImageURI, CannotParseImage
raise if @options[:raise_on_failure]
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::DEFAULT_PARSER.escape(location)
else
location
end
end
def fetch_using_http_from_parsed_uri
raise ImageFetchFailure unless @parsed_uri.is_a?(URI::HTTP)
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
location = res['Location']
raise ImageFetchFailure if location.nil? || location.empty?
@parsed_uri = URI.join(@parsed_uri, escaped_location(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
break if @property == :content_length
read_fiber = Fiber.new do
res.read_body do |str|
Fiber.yield str
end
nil
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
nil
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)
return @content_length = readable.size if @property == :content_length && readable.respond_to?(:size)
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
nil
end
else
read_fiber = Fiber.new do
while str = readable.read(LocalFileChunkSize)
Fiber.yield str
end
nil
end
end
parse_packets FiberStream.new(read_fiber)
end
def fetch_using_file_open
return @content_length = File.size?(@uri) if @property == :content_length
File.open(@uri) do |s|
fetch_using_read(s)
end
end
def fetch_using_base64(uri)
decoded = begin
uri.split(',')[1].unpack("m").first
rescue
raise CannotParseImage
end
fetch_using_read StringIO.new(decoded)
end
def parse_packets(stream)
@stream = stream
begin
@type = TypeParser.new(@stream).type unless defined?(@type)
result = case @property
when :type
@type
when :size
parse_size
when :animated
parse_animated
end
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 parser_class
klass = Parsers[@type]
raise UnknownImageType unless klass
klass
end
def parse_size
parser_class.new(@stream).dimensions
end
def parse_animated
parser_class.new(@stream).animated?
end
end

View File

@ -0,0 +1,12 @@
module FastImageParsing
class Avif < ImageBase # :nodoc:
def dimensions
bmff = IsoBmff.new(@stream)
[bmff.width, bmff.height]
end
def animated?
@stream.peek(12)[4..-1] == "ftypavis"
end
end
end

View File

@ -0,0 +1,17 @@
module FastImageParsing
class Bmp < ImageBase # :nodoc:
def dimensions
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
end
end

View File

@ -0,0 +1,76 @@
module FastImageParsing
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 FastImage::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]
data_type = @stream.read(2).unpack(@short)[0]
@stream.read(4)
if data_type == 4
data = @stream.read(4).unpack(@long)[0]
else
data = @stream.read(2).unpack(@short)[0]
@stream.read(2)
end
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
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
end

View File

@ -0,0 +1,58 @@
module FastImageParsing
class FiberStream # :nodoc:
include StreamUtil
attr_reader :pos
# read_fiber should return nil if it no longer has anything to return when resumed
# so the result of the whole Fiber block should be set to be nil in case yield is no
# longer called
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 > @str.size
unused_str = @str[@strpos..-1]
new_string = @read_fiber.resume
raise FastImage::CannotParseImage if !new_string
# we are dealing with bytes here, so force the encoding
new_string.force_encoding("ASCII-8BIT") if new_string.respond_to? :force_encoding
@str = unused_str + new_string
@strpos = 0
end
@str[@strpos, n]
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 FastImage::CannotParseImage if !new_string
new_string.force_encoding("ASCII-8BIT") if new_string.respond_to? :force_encoding
fetched += new_string.size
@str = new_string
@strpos = 0
end
@strpos = @strpos + n - discarded
@pos += n
end
end
end

View File

@ -0,0 +1,63 @@
module FastImageParsing
class Gif < ImageBase # :nodoc:
def dimensions
@stream.read(11)[6..10].unpack('SS')
end
# Checks for multiple frames
def animated?
frames = 0
# "GIF" + version (3) + width (2) + height (2)
@stream.skip(10)
# fields (1) + bg color (1) + pixel ratio (1)
fields = @stream.read(3).unpack("CCC")[0]
if fields & 0x80 != 0 # Global Color Table
# 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 # Graphic Control Extension
# extension type (1) + size (1)
size = @stream.read(2).unpack("CC")[1]
@stream.skip(size)
skip_sub_blocks
elsif block_type == 0x2C # Image Descriptor
frames += 1
return true if frames > 1
# left position (2) + top position (2) + width (2) + height (2) + fields (1)
fields = @stream.read(9).unpack("SSSSC")[4]
if fields & 0x80 != 0 # Local Color Table
# 2 * (depth + 1) colors, each occupying 3 bytes (RGB)
@stream.skip(3 * 2 ** ((fields & 0x7) + 1))
end
@stream.skip(1) # LZW min code size (1)
skip_sub_blocks
else
break # unrecognized block
end
end
false
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
end

View File

@ -0,0 +1,8 @@
module FastImageParsing
class Heic < ImageBase # :nodoc:
def dimensions
bmff = IsoBmff.new(@stream)
[bmff.width, bmff.height]
end
end
end

View File

@ -0,0 +1,9 @@
module FastImageParsing
class Ico < ImageBase
def dimensions
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
end
end

View File

@ -0,0 +1,17 @@
module FastImageParsing
class ImageBase # :nodoc:
def initialize(stream)
@stream = stream
end
# Implement in subclasses
def dimensions
raise NotImplementedError
end
# Implement in subclasses if appropriate
def animated?
nil
end
end
end

View File

@ -0,0 +1,176 @@
module FastImageParsing
# HEIC/AVIF are a special case of the general ISO_BMFF format, in which all data is encapsulated in typed boxes,
# with a mandatory ftyp box that is used to indicate particular file types. Is composed of nested "boxes". Each
# box has a header composed of
# - Size (32 bit integer)
# - Box type (4 chars)
# - Extended size: only if size === 1, the type field is followed by 64 bit integer of extended size
# - Payload: Type-dependent
class IsoBmff # :nodoc:
attr_reader :width, :height
def initialize(stream)
@stream = stream
@width, @height = nil
parse_isobmff
end
def parse_isobmff
@rotation = 0
@max_size = nil
@primary_box = nil
@ipma_boxes = []
@ispe_boxes = []
@final_size = nil
catch :finish do
read_boxes!
end
if [90, 270].include?(@rotation)
@final_size.reverse!
end
@width, @height = @final_size
end
private
# Format specs: https://www.loc.gov/preservation/digital/formats/fdd/fdd000525.shtml
# If you need to inspect a heic/heif file, use
# https://gpac.github.io/mp4box.js/test/filereader.html
def read_boxes!(max_read_bytes = nil)
end_pos = max_read_bytes.nil? ? nil : @stream.pos + max_read_bytes
index = 0
loop do
return if end_pos && @stream.pos >= end_pos
box_type, box_size = read_box_header!
case box_type
when "meta"
handle_meta_box(box_size)
when "pitm"
handle_pitm_box(box_size)
when "ipma"
handle_ipma_box(box_size)
when "hdlr"
handle_hdlr_box(box_size)
when "iprp", "ipco"
read_boxes!(box_size)
when "irot"
handle_irot_box
when "ispe"
handle_ispe_box(box_size, index)
when "mdat"
@stream.skip(box_size)
when "jxlc"
handle_jxlc_box(box_size)
else
@stream.skip(box_size)
end
index += 1
end
end
def handle_irot_box
@rotation = (read_uint8! & 0x3) * 90
end
def handle_ispe_box(box_size, index)
throw :finish if box_size < 12
data = @stream.read(box_size)
width, height = data[4...12].unpack("N2")
@ispe_boxes << { index: index, size: [width, height] }
end
def handle_hdlr_box(box_size)
throw :finish if box_size < 12
data = @stream.read(box_size)
throw :finish if data[8...12] != "pict"
end
def handle_ipma_box(box_size)
@stream.read(3)
flags3 = read_uint8!
entries_count = read_uint32!
entries_count.times do
id = read_uint16!
essen_count = read_uint8!
essen_count.times do
property_index = read_uint8! & 0x7F
if flags3 & 1 == 1
property_index = (property_index << 7) + read_uint8!
end
@ipma_boxes << { id: id, property_index: property_index - 1 }
end
end
end
def handle_pitm_box(box_size)
data = @stream.read(box_size)
@primary_box = data[4...6].unpack("S>")[0]
end
def handle_meta_box(box_size)
throw :finish if box_size < 4
@stream.read(4)
read_boxes!(box_size - 4)
throw :finish if !@primary_box
primary_indices = @ipma_boxes
.select { |box| box[:id] == @primary_box }
.map { |box| box[:property_index] }
ispe_box = @ispe_boxes.find do |box|
primary_indices.include?(box[:index])
end
if ispe_box
@final_size = ispe_box[:size]
end
throw :finish
end
def handle_jxlc_box(box_size)
jxlc = Jxlc.new(@stream)
@final_size = [jxlc.width, jxlc.height]
throw :finish
end
def read_box_header!
size = read_uint32!
type = @stream.read(4)
size = read_uint64! - 8 if size == 1
[type, size - 8]
end
def read_uint8!
@stream.read(1).unpack("C")[0]
end
def read_uint16!
@stream.read(2).unpack("S>")[0]
end
def read_uint32!
@stream.read(4).unpack("N")[0]
end
def read_uint64!
@stream.read(8).unpack("Q>")[0]
end
end
end

View File

@ -0,0 +1,52 @@
module FastImageParsing
class IOStream < SimpleDelegator # :nodoc:
include StreamUtil
end
class Jpeg < ImageBase # :nodoc:
def dimensions
exif = nil
state = 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
end
end

View File

@ -0,0 +1,13 @@
module FastImageParsing
class Jxl < ImageBase # :nodoc:
def dimensions
if @stream.peek(2) == "\xFF\x0A".b
jxlc = Jxlc.new(@stream)
[jxlc.width, jxlc.height]
else
bmff = IsoBmff.new(@stream)
[bmff.width, bmff.height]
end
end
end
end

View File

@ -0,0 +1,75 @@
module FastImageParsing
class Jxlc # :nodoc:
attr_reader :width, :height
LENGTHS = [9, 13, 18, 30]
MULTIPLIERS = [1, 1.2, Rational(4, 3), 1.5, Rational(16, 9), 1.25, 2]
def initialize(stream)
@stream = stream
@width, @height´ = nil
@bit_counter = 0
parse_jxlc
end
def parse_jxlc
@words = @stream.read(6)[2..5].unpack('vv')
# small mode allows for values <= 256 that are divisible by 8
small = get_bits(1)
if small == 1
y = (get_bits(5) + 1) * 8
x = x_from_ratio(y)
if !x
x = (get_bits(5) + 1) * 8
end
@width, @height = x, y
return
end
len = LENGTHS[get_bits(2)]
y = get_bits(len) + 1
x = x_from_ratio(y)
if !x
len = LENGTHS[get_bits(2)]
x = get_bits(len) + 1
end
@width, @height = x, y
end
def get_bits(size)
if @words.size < (@bit_counter + size) / 16 + 1
@words += @stream.read(4).unpack('vv')
end
dest_pos = 0
dest = 0
size.times do
word = @bit_counter / 16
source_pos = @bit_counter % 16
dest |= ((@words[word] & (1 << source_pos)) > 0 ? 1 : 0) << dest_pos
dest_pos += 1
@bit_counter += 1
end
dest
end
def x_from_ratio(y)
ratio = get_bits(3)
if ratio == 0
return nil
else
return (y * MULTIPLIERS[ratio - 1]).to_i
end
end
end
def parse_size_for_jxl
if @stream.peek(2) == "\xFF\x0A".b
JXL.new(@stream).read_size_header
else
bmff = IsoBmff.new(@stream)
bmff.width_and_height
end
end
end

View File

@ -0,0 +1,26 @@
module FastImageParsing
class Png < ImageBase # :nodoc:
def dimensions
@stream.read(25)[16..24].unpack('NN')
end
def animated?
# Signature (8) + IHDR chunk (4 + 4 + 13 + 4)
@stream.read(33)
loop do
length = @stream.read(4).unpack("L>")[0]
type = @stream.read(4)
case type
when "acTL"
return true
when "IDAT"
return false
end
@stream.skip(length + 4)
end
end
end
end

View File

@ -0,0 +1,7 @@
module FastImageParsing
class Psd < ImageBase # :nodoc:
def dimensions
@stream.read(26).unpack("x14NN").reverse
end
end
end

View File

@ -0,0 +1,19 @@
module FastImageParsing
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
end

View File

@ -0,0 +1,69 @@
module FastImageParsing
class Svg < ImageBase # :nodoc:
def dimensions
@width, @height, @ratio, @viewbox_width, @viewbox_height = nil
parse_svg
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
end

View File

@ -0,0 +1,16 @@
module FastImageParsing
class Tiff < ImageBase # :nodoc:
def initialize(stream)
@stream = stream
end
def dimensions
exif = Exif.new(@stream)
if exif.rotated?
[exif.height, exif.width, exif.orientation]
else
[exif.width, exif.height, exif.orientation]
end
end
end
end

View File

@ -0,0 +1,69 @@
module FastImageParsing
class TypeParser
def initialize(stream)
@stream = stream
end
# type will use peek to get enough bytes to determing the type of the image
def 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 "\xFF\x0A".b
:jxl
when "\0\0"
case @stream.peek(3).bytes.to_a.last
when 0
# http://www.ftyps.com/what.html
case @stream.peek(12)[4..-1]
when "ftypavif"
:avif
when "ftypavis"
:avif
when "ftypheic"
:heic
when "ftypmif1"
:heif
else
if @stream.peek(7)[4..-1] == 'JXL'
:jxl
end
end
# ico has either a 1 (for ico format) or 2 (for cursor) at offset 3
when 1 then :ico
when 2 then :cur
end
when "RI"
:webp if @stream.peek(12)[8..11] == "WEBP"
when "<s"
:svg if @stream.peek(4) == "<svg"
when /\s\s|\s<|<[?!]/, 0xef.chr + 0xbb.chr
# 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 1000 chars.
begin
:svg if (1..100).detect {|n| @stream.peek(10 * n).include?("<svg")}
rescue FiberError, FastImage::CannotParseImage
nil
end
end
parsed_type or raise FastImage::UnknownImageType
end
end
end

View File

@ -0,0 +1,60 @@
module FastImageParsing
class Webp < ImageBase # :nodoc:
def dimensions
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 animated?
vp8 = @stream.read(16)[12..15]
_len = @stream.read(4).unpack("V")
case vp8
when "VP8 "
false
when "VP8L"
false
when "VP8X"
flags = @stream.read(4).unpack("C")[0]
flags & 2 > 0
else
nil
end
end
private
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
[width, height]
end
end
end

View File

@ -1,67 +0,0 @@
# Poor Man's Fiber (API compatible Thread based Fiber implementation for Ruby 1.8)
# (c) 2008 Aman Gupta (tmm1)
unless defined? Fiber
require 'thread'
class FiberError < StandardError; # :nodoc:
end
class Fiber # :nodoc:
def initialize
raise ArgumentError, 'new Fiber requires a block' unless block_given?
@yield = Queue.new
@resume = Queue.new
@thread = Thread.new{ @yield.push [yield(*@resume.pop)] }
@thread.abort_on_exception = true
@thread[:fiber] = self
end
attr_reader :thread
def resume *args
raise FiberError, 'dead fiber called' unless @thread.alive?
@resume.push(args)
result = @yield.pop
result.size > 1 ? result : result.first
end
def yield *args
@yield.push(args)
result = @resume.pop
result.size > 1 ? result : result.first
end
def self.yield *args
if fiber = Thread.current[:fiber]
fiber.yield(*args)
else
raise FiberError, 'not inside a fiber'
end
end
def self.current
if Thread.current == Thread.main
return Thread.main[:fiber] ||= RootFiber.new
end
Thread.current[:fiber] or raise FiberError, 'not inside a fiber'
end
def inspect
"#<#{self.class}:0x#{self.object_id.to_s(16)}>"
end
end
class RootFiber < Fiber # :nodoc:
def initialize
# XXX: what is a root fiber anyway?
end
def self.yield *args
raise FiberError, "can't yield from root fiber"
end
end
end

5
lib/fastimage/version.rb Normal file
View File

@ -0,0 +1,5 @@
# frozen_string_literal: true
class FastImage
VERSION = '2.4.0'
end

BIN
test/fixtures/a.CR2 vendored Normal file

Binary file not shown.

BIN
test/fixtures/a.CRW vendored Normal file

Binary file not shown.

BIN
test/fixtures/animated.gif vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 978 KiB

BIN
test/fixtures/animated.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

BIN
test/fixtures/animated_without_gct.gif vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
test/fixtures/avif/fox.avif vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

BIN
test/fixtures/avif/hato.avif vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

BIN
test/fixtures/avif/kimono.avif vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

BIN
test/fixtures/avif/red_green_flash.avif vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

BIN
test/fixtures/avif/star.avifs vendored Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More