1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | import java.awt.*; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.event.*; import java.io.*; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.*; import java.util.*; public class GettingPixel extends JFrame{ private File imagefile=null; private BufferedImage bufimage=null; private JLabel label=null; private ImageIcon icon=null; private JButton button=null; private JTextArea tarea=null; public static void main(String[] args){ GettingPixel ap=new GettingPixel(); } public GettingPixel(){ super("Getting Pixel"); setSize(1220,540); label=new JLabel(); try{ imagefile=new File("robot.jpg"); bufimage=ImageIO.read(imagefile); }catch(Exception e){ } icon=new ImageIcon(bufimage); label.setIcon(icon); button=new JButton("Get Pixel"); button.addActionListener(new ButtonHandler()); tarea=new JTextArea(30,40); JScrollPane scroll=new JScrollPane(tarea); setLayout(new FlowLayout(FlowLayout.LEFT,10,10)); add(label); add(button); add(scroll); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); show(); } class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ int width=bufimage.getWidth(); int height=bufimage.getHeight(); int count=0; for(int i=0;i<height;i++){ for(int j=0;j<width;j++){ Color c=new Color(bufimage.getRGB(j,i)); tarea.append("("+j+","+i+")"+" "+c.getRed()+","+c.getGreen()+","+c.getBlue()+"\n"); } } } } } |
try{ imagefile=new File("robot.jpg"); bufimage=ImageIO.read(imagefile); }catch(Exception e){ } icon=new ImageIcon(bufimage); label.setIcon(icon);
The first line opens the image file "robot.jpg". ImageIO.read reads the image file. As image read write operation can throw an IOException, the code is placed inside a try/catch block. The BufferedImage object holds the image. The ImageIcon class is used to add the image to the label.
int width=bufimage.getWidth(); int height=bufimage.getHeight();
These two lines of code get the width and height of the image. The values will be used to access each pixel through a nested loop (one loop inside another).
int count=0; for(int i=0;i<height;i++){ for(int j=0;j<width;j++){ Color c=new Color(bufimage.getRGB(j,i)); tarea.append("("+j+","+i+")"+" "+c.getRed()+","+c.getGreen()+","+c.getBlue()+"\n"); } }
All pixels are fetched, starting from the upper left corner of the image (coordinate 0,0).
Color c=new Color(bufimage.getRGB(j,i)); tarea.append("("+j+","+i+")"+" "+c.getRed()+","+c.getGreen()+","+c.getBlue()+"\n");
This is the code to get the pixel value. The getRGB method returns a single int. To get the individual color components, we use getRed(), .getGreen(), and getBlue methods. The results are then displayed on the text area using append method.
No comments:
Post a Comment