Skip to content

Commit 065a714

Browse files
committed
perf: use header-only metadata extraction
1 parent 136f8c8 commit 065a714

File tree

2 files changed

+26
-18
lines changed

2 files changed

+26
-18
lines changed

lib/dynamic_image/metadata.rb

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
module DynamicImage
44
# = DynamicImage Metadata
55
#
6-
# Parses metadata from an image. Expects to receive image data as a
7-
# binary string.
6+
# Parses metadata from an image. Accepts a Pathname, IO, or binary string.
87
class Metadata
98
def initialize(data)
109
@data = data
@@ -60,26 +59,35 @@ def metadata
6059
@metadata ||= read_metadata
6160
end
6261

63-
def read_image
64-
yield reader.read.autorot
65-
end
66-
6762
def reader
6863
@reader ||= DynamicImage::ImageReader.new(@data)
6964
end
7065

7166
def read_metadata
72-
read_image do |image|
73-
height = if image.get_fields.include?("page-height")
74-
image.get("page-height")
75-
else
76-
image.get("height")
77-
end
78-
79-
{ width: image.get("width"),
80-
height:,
81-
colorspace: image.get("interpretation") }
82-
end
67+
image = reader.read
68+
69+
width = image.get("width")
70+
height = if image.get_fields.include?("page-height")
71+
image.get("page-height")
72+
else
73+
image.get("height")
74+
end
75+
76+
width, height = height, width if rotated?(image)
77+
78+
{ width:, height:, colorspace: image.get("interpretation") }
79+
end
80+
81+
def orientation(image)
82+
return 1 unless image.get_fields.include?("orientation")
83+
84+
image.get("orientation")
85+
rescue Vips::Error
86+
1
87+
end
88+
89+
def rotated?(image)
90+
orientation(image).between?(5, 8)
8391
end
8492
end
8593
end

lib/dynamic_image/model.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def to_param
106106
private
107107

108108
def read_image_metadata
109-
metadata = DynamicImage::Metadata.new(data)
109+
metadata = DynamicImage::Metadata.new(Pathname(data_file_path))
110110
@valid_image = false
111111
return unless metadata.valid?
112112

0 commit comments

Comments
 (0)