class PNM::Image
Abstract base class for PBM
, PGM
, and PPM
images.
Images can be created from pixel values, see PNM.create
, or read from a file or I/O stream, see PNM.read
.
See PNM
module for examples.
Attributes
An optional multiline comment string (or nil
).
The height of the image in pixels.
The maximum gray or color value (for PBM always set to 1). See PNM.create
for details.
The pixel data, given as a two-dimensional array. See PNM.create
for details.
The width of the image in pixels.
Public Class Methods
Creates an image from a two-dimensional array of bilevel, gray, or RGB values.
This method should be called as PNM.create
. See there for a description of pixel data formats and available options.
# File lib/pnm/image.rb, line 41 def self.create(pixels, type: nil, maxgray: nil, comment: nil) assert_valid_array(pixels) assert_valid_maxgray(maxgray) assert_valid_comment(comment) type = sanitize_and_assert_valid_type(type) type ||= detect_type(pixels, maxgray) # except for type detection, the maxgray option must be ignored for PBM maxgray = nil if type == :pbm image_class = case type when :pbm PBMImage when :pgm PGMImage when :ppm PPMImage end image_class.new(pixels, maxgray, comment) end
Public Instance Methods
Equality — Two images are considered equal if they have the same pixel values, type, maxgray, and comments.
# File lib/pnm/image.rb, line 127 def ==(other) return true if other.equal?(self) return false unless other.instance_of?(self.class) type == other.type && maxgray == other.maxgray && comment == other.comment && pixels == other.pixels end
Returns a string with a short image format description.
# File lib/pnm/image.rb, line 114 def info "#{type.to_s.upcase} #{width}x#{height} #{type_string}" end
Returns a string representation for debugging.
# File lib/pnm/image.rb, line 121 def inspect # implemented by subclasses end
The type of the image. See PNM.create
for details.
# File lib/pnm/image.rb, line 14 def type # implemented by subclasses end
Writes the image to file
(a filename or an IO object).
When add_extension
is set to true
(default: false
) the appropriate file extension is added to the provided filename (.pbm
, .pgm
, or .ppm
).
The encoding can be set using the encoding
keyword argument, valid options are :binary
(default) and :ascii
.
Returns the number of bytes written.
# File lib/pnm/image.rb, line 96 def write(file, add_extension: false, encoding: :binary) content = case encoding when :ascii to_ascii when :binary to_binary end if file.is_a?(String) filename = add_extension ? "#{file}.#{type}" : file File.binwrite(filename, content) else file.binmode file.write content end end