0

I want to display image on the Jpanel. For standard screen size the image of width x height = 220x45 is displayed properly. To the constructor ImagePanel I'm passing the image url with it's height and width and the image is being displayed properly. Now if I launch the Swing application on large monitors the image gets blurry, so I make another image of high resolution dpi. Here how to determine the image's new height and width for resizing the image for different screen sizes?

imagePanel = new ImagePanel("images/logo-header.png", 220, 45);

public ImagePanel(String url, int w, int h) {
    try {    
       InputStream is = getFileFromResourceAsStream(url);
       image = ImageIO.read(is);
       imageurl = url;

       width=w;
       height=h;
       isScaled = true;
       outputImage = new BufferedImage(w,h, image.getType());
     
   } catch (IOException ex) {
       ex.printStackTrace();
   }
}
techJava
  • 151
  • 8
  • 1
    Your question is not clear to me. The image has its own width and height. Why do you set its width and height to arbitrary values? Do you want the image to always fill the entire screen? Do you want it to always fill the entire `JFrame` of your _Swing_ application? Are you asking how to write java code to properly scale an image? – Abra Apr 10 '21 at 11:12
  • If I don't pass the height and width, the new high resolution image is not displayed properly on JPanel, only a part of it is displayed. I want image to display as whole properly on JPanel on all screen sizes. So my question is how to scale the image for different screen sizes ? – techJava Apr 10 '21 at 11:27
  • Does this help? https://stackoverflow.com/questions/5895829/resizing-image-in-java – Abra Apr 10 '21 at 11:36
  • In the above SO answer they are passing newHeight and newWidth to getScaledInstance() method. But it's not known as how they calculating newHeight and newWidth of the image? – techJava Apr 10 '21 at 11:47
  • How do you calculate new dimensions of image? Are you asking how to get size of the screen? – Abra Apr 10 '21 at 11:48
  • For different screen sizes I need to pass different widths and heights of an image so that it fits and displays appropriately within JPanel. With the help of Screen size, is there any way to calculate newWidth and newHeight of an image, so that high resolution image of size say w x h = 2840 x 507 is displayed completely in JPanel? – techJava Apr 10 '21 at 12:01
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/230972/discussion-between-abra-and-techjava). – Abra Apr 10 '21 at 12:05
  • - easiest way is to do custom painting. You just use the `drawImage(...)` method of the Graphics object. It will dynamically resize the image as the size of the panel changed. – camickr Apr 10 '21 at 15:26

0 Answers0