Example of using Java API to create and save an image with an alpha channel (translucent).
import ij.process.*
import java.awt.*
import java.awt.color.*
import java.awt.image.*
import javax.imageio.ImageIO
def ColorProcessor cp // = ...
def ByteProcessor alpha // = ...
def BufferedImage bi = createTransparent(cp, alpha)
ImageIO.write(bi, "PNG", new File("transparent-image.png"))
// Pixels with alpha equal 0 will be transparent, pixels with alpha=255 will
// be opaque, values between 0 and 255 will vary transparency.
def createTransparent(ColorProcessor src, ByteProcessor alpha) {
def cs = ColorSpace.getInstance(ColorSpace.CS_sRGB)
def bits = [8, 8, 8, 8] as int[]
def cm = new ComponentColorModel(cs, bits, true, false,
Transparency.BITMASK, DataBuffer.TYPE_BYTE)
def raster = cm.createCompatibleWritableRaster(src.width, src.height)
def dataBuffer = raster.dataBuffer as DataBufferByte
final data = dataBuffer.data
final n = (src.pixels as int[]).length
final r = new byte[n]
final g = new byte[n]
final b = new byte[n]
final a = (byte[]) alpha.pixels
src.getRGB(r, g, b)
for (int i = 0; i < n; ++i) {
final int offset = i * 4
data[offset] = r[i]
data[offset + 1] = g[i]
data[offset + 2] = b[i]
data[offset + 3] = a[i]
}
return new BufferedImage(cm, raster, false, null)
}