Class: FreeImage::MemoryStream

Inherits:
FFI::AutoPointer
  • Object
show all
Defined in:
lib/free-image/sources/memory.rb

Overview

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.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bytes = nil) ⇒ MemoryStream

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.



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/free-image/sources/memory.rb', line 51

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

Class Method Details

.release(ptr) ⇒ Object



40
41
42
43
# File 'lib/free-image/sources/memory.rb', line 40

def self.release(ptr)
  FreeImage.FreeImage_CloseMemory(ptr)
  FreeImage.check_last_error
end

Instance Method Details

#bytesObject

Returns the bytes of the memory stream.



89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/free-image/sources/memory.rb', line 89

def bytes
  # Reset memory to start
  self.seek(0, ::IO::SEEK_SET)

  # Create a buffer to store the memory
  buffer = FFI::MemoryPointer.new(FFI::Type::CHAR.size, self.count)
  FreeImage.check_last_error
  written = FreeImage.FreeImage_ReadMemory(buffer, FFI::Type::CHAR.size, self.count, self)

  # Return a string
  buffer.get_bytes(0, FFI::Type::CHAR.size * count)
end

#countObject

Returns the size of the memory stream.



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

def count
  last_position = self.position

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

  # Restore position
  self.seek(last_position, ::IO::SEEK_SET)

  count
end

#positionObject



63
64
65
66
67
# File 'lib/free-image/sources/memory.rb', line 63

def position
  result = FreeImage.FreeImage_TellMemory(self)
  FreeImage.check_last_error
  result
end

#seek(amount, whence = IO::SEEK_SET) ⇒ Object



69
70
71
72
# File 'lib/free-image/sources/memory.rb', line 69

def seek(amount, whence=IO::SEEK_SET)
  FreeImage.FreeImage_SeekMemory(self, amount, whence)
  FreeImage.check_last_error
end