Class: FreeImage::IO

Inherits:
AbstractSource show all
Defined in:
lib/free-image/sources/io.rb

Overview

Summary

Supports loading and saving images to a Ruby IO stream.

Usage

# Read an image from an io stream string
file = ::File.open('test/fixtures/lena.png', :encoding => Encoding::BINARY)
image = FreeImage::IO.open(file)

# Save an image to a byte string
dest = FreeImage::IO.new(::File.open('test/fixtures/lena_new.png', :encoding => Encoding::BINARY))
image.save(dest, :jpeg)
dest.bytes

Instance Method Summary collapse

Methods inherited from AbstractSource

#open

Constructor Details

#initialize(io) ⇒ IO

Create a new FreeImage::IO instance that can read and write image data from a Ruby IO stream.

Parameters

io

A standard Ruby io stream such as a file.



74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/free-image/sources/io.rb', line 74

def initialize(io)
  @io = io

  @handle = FFI::MemoryPointer.new(:ulong)
  @handle.put_ulong(0, self.object_id)

  @ffi_io = FreeImage::IOStruct.new
  @ffi_io[:read_proc] = method(:read)
  @ffi_io[:write_proc] = method(:write)
  @ffi_io[:seek_proc] = method(:seek)
  @ffi_io[:tell_proc] = method(:tell)
end

Instance Method Details

#formatObject

call-seq:

handle.image_type -> :format

Returns the image format for a memory stream. If the image format cannot be determined the :unknown will be returned.



93
94
95
96
97
98
99
# File 'lib/free-image/sources/io.rb', line 93

def format
  result = FreeImage.FreeImage_GetFileTypeFromHandle(@ffi_io, @handle, 0)
  FreeImage.check_last_error
  result
rescue Errno::EINVAL => e
  :unknown
end

#save(bitmap, format, flags = 0) ⇒ Object

:call-seq:

file.save(format = nil, flags = 0) -> boolean

Saves an image to a file.

Parameters

format

The format to save the image to.

flags

Format specific flags that control how a bitmap is saved. These flags are defined as constants on the AbstractSource class. Flags can be combined using Ruby’s bitwise or operator (|)

Usage

image = Bimap.open('<path_to_file>')
source = FreeImage::File.new('<path_to_new_file>')
source.save(image, :jpeg, AbtractSource::JPEG_QUALITYSUPERB | AbtractSource::JPEG_PROGRESSIVE)


119
120
121
122
123
# File 'lib/free-image/sources/io.rb', line 119

def save(bitmap, format, flags = 0)
  result = FreeImage.FreeImage_SaveToHandle(format, bitmap, @ffi_io, @handle, flags)
  FreeImage.check_last_error
  result
end