Class: SmartImage::JavaCanvas

Inherits:
BaseCanvas show all
Defined in:
lib/smart_image/java_canvas.rb

Overview

Canvas object backed by Java Graphics2D

Instance Method Summary collapse

Methods inherited from BaseCanvas

#destroyed?

Constructor Details

#initialize(width, height) ⇒ JavaCanvas

Returns a new instance of JavaCanvas.



12
13
14
# File 'lib/smart_image/java_canvas.rb', line 12

def initialize(width, height)
  @canvas = BufferedImage.new width, height, BufferedImage::TYPE_INT_ARGB
end

Instance Method Details

#alpha_mask(image_data, options = {}) ⇒ Object

Load the given file as an alpha mask for the image



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/smart_image/java_canvas.rb', line 39

def alpha_mask(image_data, options = {})
  input_stream = ByteArrayInputStream.new image_data.to_java_bytes
  mask = ImageIO.read input_stream
  
  width = mask.width
  image_data, mask_data = Java::int[width].new, Java::int[width].new
  
  mask.height.times do |y|
    # fetch a line of data from each image
    @canvas.get_rgb 0, y, width, 1, image_data, 0, 1
    mask.get_rgb 0, y, width, 1, mask_data, 0, 1
    
    width.times do |x|
      # mask away the alpha
      color = image_data[x] & 0x00FFFFFF 
      
      # turn red from the mask into alpha
      alpha = (mask_data[x] & 0x00FF0000) << 8 
      
      image_data[x] = color | alpha
    end
    
    @canvas.set_rgb 0, y, width, 1, image_data, 0, 1
  end
end

#composite(image_data, options = {}) ⇒ Object

Composite the given image data onto the canvas

Raises:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/smart_image/java_canvas.rb', line 21

def composite(image_data, options = {})
  info = SmartImage.info image_data
  opts = {
    :width  => info.width,
    :height => info.height,
    :x => 0,
    :y => 0
  }.merge(options)
  
  input_stream = ByteArrayInputStream.new image_data.to_java_bytes
  image = ImageIO.read input_stream
  raise FormatError, "invalid image" unless image
  
  graphics = @canvas.graphics
  graphics.draw_image image, opts[:x], opts[:y], opts[:width], opts[:height], nil
end

#destroyObject

Stub out destroy since Java actually garbage collects crap, unlike… C



17
18
# File 'lib/smart_image/java_canvas.rb', line 17

def destroy
end

#encode(format, options = {}) ⇒ Object

Encode the image to the given format



66
67
68
69
70
# File 'lib/smart_image/java_canvas.rb', line 66

def encode(format, options = {})
  output_stream = ByteArrayOutputStream.new
  ImageIO.write(@canvas, format.to_s, output_stream)
  String.from_java_bytes output_stream.to_byte_array
end