-3

I tried to read rgb of specific pixels however i was getting IOException.
I couldnt find any reson so yet i tried to run program from this site link but im still getting IOException.
So can this be because of JRE or my IDE which is Eclipse?

import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class GetPixelColor
{
  public static void main(String args[]) throws IOException{
  File file= new File("rockface.jpg");
  BufferedImage image = ImageIO.read(file);
  // Getting pixel color by position x=100 and y=40 
  int clr=  image.getRGB(100,40); 
  int  red   = (clr & 0x00ff0000) >> 16;
  int  green = (clr & 0x0000ff00) >> 8;
  int  blue  =  clr & 0x000000ff;
  System.out.println("Red Color value = "+ red);
  System.out.println("Green Color value = "+ green);
  System.out.println("Blue Color value = "+ blue);
  }
}
VirtualTroll
  • 3,077
  • 1
  • 30
  • 47
Pirey
  • 23
  • 2

4 Answers4

1

That's probably because that program you linked is referencing an image that you haven't in your path.

Add the following line after File constructor to check if the file you are looking for exist:

File file= new File("rockface.jpg");
if (file.exists()){
   //OK
}else{
   //you should have I/O Exception when the code reach ImageIO.read(file);

}
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
1

According to JavaDoc, this (likely) is the method that is throwing the IOException:

ImageIO#read(File f)

From the documentation:

Throws:

IllegalArgumentException - if input is null.

IOException - if an error occurs during reading.

This is most likely due to not being able to find the File you specified. Try moving it to the classpath or project root.

Community
  • 1
  • 1
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
0

I can't remember the exact details, but I've heard other people asking about IOExceptions with Eclipse.

It's probably the case that your files are not in the running directory of your project. I can't remember how eclipse is set up, but try moving the files into whatever folder holds the .class files, or just otherwise play around with the file's location.

Ken Wayne VanderLinde
  • 18,915
  • 3
  • 47
  • 72
0

A solution would be to specify the absolute path (assuming you are using windows that would be c:....\etc..) otherwise you will have to use the relative path.
To know in which folder your application is search, you can use :

System.getProperty("user.dir");

VirtualTroll
  • 3,077
  • 1
  • 30
  • 47