class FreeImage::MemoryStream

  1. lib/free-image/sources/memory.rb
Superclass: FreeImage::FFI::AutoPointer

Wrapper for a FreeImage memory stream which allows images to be read and written to memory. Memory streams are usefule for storing images as blobs in a database or writing them to an to a Internet stream.

Methods

Public Class

  1. new
  2. release

Public Instance

  1. bytes
  2. count

Public Class methods

new (bytes = nil)

Create a new memory stream.

Parameters

bytes

If specified, a binary encoded Ruby string that stores image data. FreeImage will treat the string as read-only. If not specified, a writable MemoryStream is created.

[show source]
# File lib/free-image/sources/memory.rb, line 48
def initialize(bytes = nil)
  ptr = if bytes
    buf = FFI::MemoryPointer.from_string(bytes)
    FreeImage.FreeImage_OpenMemory(buf, bytes.bytesize)
  else
    FreeImage.FreeImage_OpenMemory(nil, 0)
  end
  FreeImage.check_last_error

  super(ptr)
end
release (ptr)
[show source]
# File lib/free-image/sources/memory.rb, line 37
def self.release(ptr)
  FreeImage.FreeImage_CloseMemory(ptr)
  FreeImage.check_last_error
end

Public Instance methods

bytes ()

Returns the bytes of the memory stream.

[show source]
# File lib/free-image/sources/memory.rb, line 79
def bytes
  size = FFI::Type::CHAR.size

  # Reset memory to start
  FreeImage.FreeImage_SeekMemory(self, 0, ::IO::SEEK_SET)
  FreeImage.check_last_error

  buffer = FFI::MemoryPointer.new(FFI::Type::CHAR, size * count)
  FreeImage.check_last_error
  size = FreeImage.FreeImage_ReadMemory(buffer, size, count, self)
  buffer.null? ? nil : buffer.read_string
end
count ()

Returns the size of the memory stream.

[show source]
# File lib/free-image/sources/memory.rb, line 61
def count
  # Store current position
  pos = FreeImage.FreeImage_TellMemory(self)
  FreeImage.check_last_error

  # Go to end of stream to get length
  FreeImage.FreeImage_SeekMemory(self, 0, ::IO::SEEK_END)
  FreeImage.check_last_error
  count = FreeImage.FreeImage_TellMemory(self)

  # Restore position
  FreeImage.FreeImage_SeekMemory(self, pos, ::IO::SEEK_SET)
  FreeImage.check_last_error

  count
end