Images
Draw a picture in memory, change it with a Java2D operation, save it as a PNG file and read it back.
What you will learn#
BufferedImageandcreateGraphics(),- the colour of a pixel as a number,
RescaleOp: one call changes the whole picture,ImageIO.writeandImageIO.read.
The program#
# Tutorial 27: images - draw, change and save a picture with Java2D and ImageIO (no window)
load "java.ring"
using {
"java.awt"
"java.awt.color"
"java.awt.image"
}
# 1. a picture in memory: 100 x 60 pixels with a red background and a blue square
oImage = (new BufferedImage).@New([100,60,1])
oG = oImage.createGraphics()
oG.setColor(jColor(220,30,30))
oG.fillRect(0,0,100,60)
oG.setColor(jColor(30,30,220))
oG.fillRect(60,10,30,30)
oG.dispose()
? "size " + oImage.getWidth() + " x " + oImage.getHeight()
# 2. the colour of a pixel is a number 0xRRGGBB
? "pixel (5,5) = " + (oImage.getRGB([5,5]) & 16777215)
? "pixel (70,20) = " + (oImage.getRGB([70,20]) & 16777215)
# 3. a Java2D operation changes the whole picture in one call: invert the colours
oInvert = (new RescaleOp).@New([-1,255,NULL])
oNegative = oInvert.filter(oImage,NULL)
? "inverted (5,5) = " + (oNegative.getRGB([5,5]) & 16777215)
# 4. save as a PNG file and read it back
oFile = jNew("java.io.File",[jProperty("java.io.tmpdir") + "/ringjava_tutorial.png"])
jStatic("javax.imageio.ImageIO","write",[oImage,"png",oFile])
? "saved " + oFile.length() + " bytes? " + (oFile.length() > 100)
oBack = jStatic("javax.imageio.ImageIO","read",[oFile])
? "read back " + oBack.getWidth() + " x " + oBack.getHeight() + ", same pixel: " + (oBack.getRGB([70,20]) = oImage.getRGB([70,20]))
oFile.delete()
# 5. a loop over the pixels is a call into Java for every pixel: count the blue ones for a small picture
nBlue = 0
for nX = 55 to 95
if (oImage.getRGB([nX,25]) & 255) > 200
nBlue++
ok
next
? "blue pixels on a line: " + nBluesize 100 x 60
pixel (5,5) = 14425630
pixel (70,20) = 1973980
inverted (5,5) = 2351585
saved 269 bytes? 1
read back 100 x 60, same pixel: 1
blue pixels on a line: 30How it works#
Every call from Ring to Java has a cost, so a loop over thousands of pixels is slow. Use an operation of Java2D (RescaleOp, ColorConvertOp, drawImage with another size) for the whole picture, and a loop only for the few pixels you need. The application ImageViewer uses the same operations behind its buttons.
Exercises#
- Make the picture gray with
ColorConvertOp. - Draw a text with
drawStringand save the picture as a JPEG. - Make a thumbnail of half the size with
drawImage.