Site iconJava PDF Blog

What are Blend modes in Java?

blend modes in PDF

Blend modes allow you to draw in much more interesting ways than just over-writing one color with another. They are also very easy to use in Java from both Swing (Java2D) and JavaFX!

First of all let’s take a look into how blend modes can be applied in Java2D. Unfortunately, there isn’t out of the box support for the blend modes used in the PDF specification, so we have to do it ourselves.

Luckily what we do have is the ability to implement them via the Composite/CompositeContext interfaces. The Composite gets passed to the Graphics2D object using the setComposite(~) method. The CompositeContext is used within the Composite and is the returned variable when createContext(~) is called.

Inside of CompositeContext, the method compose(~) is where the blending happens. compose() passes in three rasters; the first source image, the second source image and the WritableRaster which is where the output goes. With the first two rasters, you can loop through and find the pixel ARGB value for each pixel.

Multply blends inside of our Swing viewer

Now let’s look at how JavaFX approaches blend modes. In FX you can pass a blend mode straight to a Node using setBlendMode(~) and passing in the specified BlendMode enum. Best of all, all the blend modes specified in the PDF specification are all in JavaFX by default (as well as Blend Modes you would expect from Photoshop and the like)!

Blends applied using the .setBlendMode(BlendMode blend) method

Abstractions like these are one of the things I really like about JavaFX, being able to simply declare which type of blend mode I want to use and letting the API do the rest of the work makes things much simpler.