0
try {
    try {
        Image img = ImageIO.read(new File("target.png"));
        String imgpath = "target.png";
        } catch (IOException e) {
        e.printStackTrace();}
    } finally {
        int width = img.getWidth();
        int height = img.getHeight();
    }
}

I have already created "img" in this line:

Image img = ImageIO.read(new File("target.png"));

But when I want to get the dimensions of "img" in these lines;

int width = img.getWidth();
int height = img.getHeight();

it gives me this error: img cannot be resolved

Could anyone tell me what I did wrong pls

GR_ Gamer
  • 7
  • 1
  • 1

1 Answers1

0

The problem here is "img" is only defined in the inner "try" block. Try this:

Image img = null;
try {
    try {
        img = ImageIO.read(new File("target.png"));
        String imgpath = "target.png";
    } catch (IOException e) {
        e.printStackTrace();
    }
} finally {
    if (img != null) {
        int width = img.getWidth();
        int height = img.getHeight();
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Anubhav Sharma
  • 159
  • 1
  • 12