Image Processing In Java – Get and Set Pixels
Last Updated :
14 Nov, 2021
Prerequisite – Image Processing in Java – Read and Write
In this set, we will learn about the pixels of images, how we can get pixel values of an image and how to set pixel values in an image using Java programming language. Pixels are the smallest unit of an image which consists of four components Alpha (transparency measure), Red, Green, Blue, and in short (ARGB). The value of all the components lies between 0 and 255, both inclusive. Zero means the component is absent, and 255 represents the component is fully present.
Note: Since 28 = 256 and the value of the pixel components lie between 0 and 255, so we need only 8-bits to store the values.
So, the total number of bits required to store the ARGB values is 8*4=32 bits or 4 bytes. As the order signifies, Alpha acquires the leftmost 8 bits. Blue acquires the rightmost 8 bits.
Thus the bit position:
- For the blue component being 7-0,
- For green component being 15-8,
- For the red component being 23-16,
- For alpha component being 31-24,
Pictorial Representation of Indexes:
Example:
Java
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class GetSetPixels {
public static void main(String args[])
throws IOException
{
BufferedImage img = null ;
File f = null ;
try {
f = new File(
"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png" );
img = ImageIO.read(f);
}
catch (IOException e) {
System.out.println(e);
}
int width = img.getWidth();
int height = img.getHeight();
int p = img.getRGB( 0 , 0 );
int a = (p >> 24 ) & 0xff ;
int r = (p >> 16 ) & 0xff ;
int g = (p >> 8 ) & 0xff ;
int a = p & 0xff ;
a = 255 ;
r = 100 ;
g = 150 ;
b = 200 ;
p = (a << 24 ) | (r << 16 ) | (g << 8 ) | b;
img.setRGB( 0 , 0 , p);
try {
f = new File(
"C:/Users/hp/Desktop/Image Processing in Java/GFG.png" );
ImageIO.write(img, "png" , f);
}
catch (IOException e) {
System.out.println(e);
}
}
}
|
Output –
Note: This code will not run on online IDE as it needs an image on disk.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...