Java
Swing - Graphics LESSON NOTE
Images
can be broken down into small dots called pixels. Each pixel has a single colour. MEGAPIXEL The
word megapixel means “millions of pixels”.
A 12 megapixel camera takes images that consist of about 12 million
pixels. PIXEL COORDINATES Each
pixel has a coordinate. The top left
pixel is at (0,0).
The one to the next of it is at (0,1). The one beneath (0,0)
is at (0,1). This
is the same system used as when we are drawing shapes on a canvas so we won’t
spend anymore time on this idea. SETTING A PIXEL’S COLOUR This
is fairly simple. First we create a
color object. Then we specify which
pixel is to get that colour.
img.setRGB(x,y,c.getRGB()); EXAMPLE – SETTING A
PIXEL’S COLOUR
The
code above creates the following: GETTING A PIXEL’S COLOUR Let’s
assume we have a BufferedImage object called img. We
can get an encoded RGB value (integer) for a specific pixel by using: img.getRGB(x,y) Where
x and y are the coordinates of the pixel. However,
working with an encoded RGB value is a pain.
Thankfully, we can convert that to a Color object by using the
following constructor: Color(int RGBValue, boolean hasAlpha) Combining
everything, we get the following statement: Color pixelColor
= new Color(img.getRGB(x,y),
true); PIXEL BY PIXEL
MANIPULATION
for(int x = 0;
x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight();
y++)
{
//Get the colour of the pixel at (x,y) here //Figure out a new colour
for that pixel //Set the new colour
of the pixel at (x,y) here
} } EXAMPLE 1 – MAKING AN IMAGE LIGHTER & DARKER The
following code will go through an image pixel by pixel and create a darker
and lighter version of that image.
The
code above will create EXAMPLE 2 – GRAYSCALE In this example, we will alter an image’s
pixels so that the image is grayscale instead of full colour.
The
above code will create: |
||||||
|
||||||
|