2

I have a javafx.scene.image.Image and need to create a new image with a sub rectangle. I have tried the PixelReader.getPixels but it ask for a WritablePixelFormat and I don't know how to use it.

  • Can you post some executable sample code? I have done [similar things before](http://stackoverflow.com/questions/12941600/reduce-number-of-colors-and-get-color-of-a-single-pixel) and I did not need to directly interact with a `WritablePixelFormat`. – jewelsea Nov 17 '12 at 00:54

1 Answers1

0

What I recommend you to do is to instantiate a Canvas just the size of your sub-rectangle and, using its GraphicsContext, draw the piece of your source image there. After doing that, use the Canvas as you would have used an ImageView.

I am doing this in a class that cuts an image in slices and gives you those.

Basically the steps are:

  1. Create a Canvas node of the size of your sub-rectangle
  2. Obtain the GraphicsContext of that Canvas
  3. Using your image as the source, draw onto that Canvas
  4. Insert your Canvas in your scene, or wherever appropriate

This is the GraphicsContext to do the drawing:

public void drawImage(Image img,
             double srcX,
             double srcY,
             double srcWidth,
             double srcHeight,
             double destX,
             double destY,
             double destWidth,
             double destHeight)

Here is my code for drawing the "slices" of an image, in Scala:

import javafx.scene.image.Image
import javafx.scene.canvas.Canvas

class Slicer(val img: Image, val xAmount: Int, val yAmount: Int) {

  val sliceWidth = img.getWidth() / xAmount
  val sliceHeight = img.getHeight() / yAmount

  def sliceAt(x: Int, y: Int): Canvas = {
    val canvas = new Canvas(sliceWidth, sliceHeight)
    val grContext = canvas.getGraphicsContext2D()

    val (sourceX, sourceY) = coordinatesOfSliceAt(x, y)
    val (destX, destY) = (0, 0)

    grContext.drawImage(img,
      sourceX, sourceY, sliceWidth, sliceHeight,
      destX, destY, sliceWidth, sliceHeight)

    canvas
  }

  def coordinatesOfSliceAt(x: Int, y: Int): (Int, Int) = {
    val coordX = ((x - 1) * sliceWidth).toInt
    val coordY = ((y - 1) * sliceHeight).toInt
    (coordX, coordY)
  }

}

I came to this solution when I came across this:

http://docs.oracle.com/javafx/2/image_ops/jfxpub-image_ops.htm

The relevant part was that they draw pieces of the original image to a Canvas. So, no need to deal with PixelReaders or Writers.

Sebastian N.
  • 1,962
  • 15
  • 26