Skip to content

Commit d0f2c22

Browse files
authored
Merge pull request #290 from Nakilon/master
Image#to_enum -- a faster addition to #to_a
2 parents 4dd7f22 + 619f65c commit d0f2c22

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

lib/vips/image.rb

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1129,14 +1129,10 @@ def [] index
11291129
end
11301130
end
11311131

1132-
# Convert to an Array. This will be slow for large images.
1132+
# Convert to an Enumerator. Similar to `#to_a` but lazier.
11331133
#
1134-
# @return [Array] array of Fixnum
1135-
def to_a
1136-
# we render the image to a big string, then unpack
1137-
# as a Ruby array of the correct type
1138-
memory = write_to_memory
1139-
1134+
# @return [Enumerator] Enumerator of Enumerators of Arrays of Numerics
1135+
def to_enum
11401136
# make the template for unpack
11411137
template = {
11421138
char: "c",
@@ -1151,14 +1147,22 @@ def to_a
11511147
dpcomplex: "d"
11521148
}[format] + "*"
11531149

1154-
# and unpack into something like [1, 2, 3, 4 ..]
1155-
array = memory.unpack(template)
1150+
# we render the image to a big string, then unpack into
1151+
# one-dimensional array as a Ruby array of the correct type
1152+
array = write_to_memory.unpack template
1153+
1154+
# gather bands of a pixel together
1155+
pixel_array = array.each_slice bands
11561156

1157-
# gather band elements together
1158-
pixel_array = array.each_slice(bands).to_a
1157+
# gather pixels of a row together
1158+
pixel_array.each_slice width
1159+
end
11591160

1160-
# build rows
1161-
pixel_array.each_slice(width).to_a
1161+
# Convert to an Array. This will be slow for large images.
1162+
#
1163+
# @return [Array] Array of Arrays of Arrays of Numerics
1164+
def to_a
1165+
to_enum.to_a
11621166
end
11631167

11641168
# Return the largest integral value not greater than the argument.

0 commit comments

Comments
 (0)