Oracle GlassFish Server 3.0.1 Scripting Framework Guide

ProcedureTo Add Java2D Code to a Rails Controller

With this task, you will add the code to process your JPEG image.

  1. Add the following line to HomeController, right after the class declaration:


    include Java

    This line is necessary for you to access any Java libraries from your controller.

  2. Create a constant for the BufferedImage class so that you can refer to it by the shorter name:


    BI = java.awt.image.BufferedImage
  3. Add an empty action, called seeimage, at the end of the controller:


    def seeimage
    end

    This action is mapped to the seeimage.html.erb view.

  4. Give controller access to your image file using java.io.File, making sure to use the name of your image in the path to the image file. Place the following line inside the seeimage action:


    filename = "#{RAILS_ROOT}/public/images/kids.jpg"
    imagefile = java.io.File.new(filename)

    Notice that you do not need to declare the types of the variables, filename or imagefile. JRuby can tell that filename is a String and imagefile is a java.io.File instance because that is what you assigned them to be.

  5. Read the file into a BufferedImage object and create a Graphics2D object from it so that you can perform the image processing on it. Add these lines directly after the previous two lines:


    bi = javax.imageio.ImageIO.read(imagefile)
    w = bi.getWidth()
    h = bi.getHeight()
    bi2 = BI.new(w, h, BI::TYPE_INT_RGB)
    big = bi2.getGraphics()
    big.drawImage(bi, 0, 0, nil)
    bi = bi2
    biFiltered = bi

    Refer to The Java Tutorial for more information on the Java 2D API.

    The important points are :

    • You can call Java methods in pretty much the same way in JRuby as you do in Java code.

    • You do not have to initialize any variables.

    • You can just create a variable and assign anything to it. You do not need to give it a type.

  6. Add the following code to convert the image to grayscale:


    colorSpace = java.awt.color.ColorSpace.getInstance(
    java.awt.color.ColorSpace::CS_GRAY)
    op = java.awt.image.ColorConvertOp.new(colorSpace, nil)
    dest = op.filter(biFiltered, nil)
    big.drawImage(dest, 0, 0, nil);
  7. Stream the file to the browser:


    os = java.io.ByteArrayOutputStream.new
    javax.imageio.ImageIO.write(biFiltered, "jpeg", os)
    string = String.from_java_bytes(os.toByteArray)
    send_data string, :type => "image/jpeg", :disposition => "inline", 
    	:filename => "newkids.jpg"

    Sometimes you need to convert arrays from Ruby to Java code or from Java code to Ruby. In such cases, you need to use the from_java_bytes routine to convert the bytes in the output stream to a Ruby string so that you can use it with send_data to stream the image to the browser. JRuby provides some other routines for converting types, such as to_java to convert from a Ruby Array to a Java String. See Conversion of Types.