views:

63

answers:

2

hi,

I'm trying to write an application where I want to add different pictures on a Jpanel. Everything works fine except for the JPG format which displays very bad quality images. This is how I do the drawing :

class draw extends Canvas 
{
    Dimension canvasSize = new Dimension(400, 400);
    String fileName;

    public void paint(Graphics g) 
    {       
        if(this.fileName!=null)
        {
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Image img = toolkit.getImage(fileName);
            g.drawImage(img, 0, 0, this);
        }                   
    }
    public void setFileName(String name)
    {
        this.fileName=name;
    }

    public Dimension getMinimumSize()
    {
        return canvasSize;  
    }

    public Dimension getPreferredSize()
    {   
        return canvasSize;
    }
}

Is there a way such that JPG format is covered ?

+4  A: 

This is probably because you're stretching (or compressing) the image to the size of the canvas. JPEG images don't look great when you scale them, particularly if you're scaling up. Try an image that's the same size as (or close to) your canvas. You can also get the height and width of the JPEG from the Image class and display it in its original dimensions. Sun's Drawing an Image tutorial shows how to do this.

Bill the Lizard
Also, this article by Chris Campbell is an awesome resource for image scaling both generally and specifically for Java: http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
Ash
+2  A: 

The posted code indicates that the OP is painting the image at its original size. So my comments about the code:

a) You say you want to add the image to a JPanel, yet for some reason you are extending Canvas. Stick with Swing components. Then if you need to do custom painting you would override the paintComponent() method NOT the paint method.

b) When you do use custom painting, you should never read the image in the painting method. This method can be called numerous times. It possible that the image has not been completely read into memory. I know Swing will automatically repaint as more of the image is read, I'm not sure how the AWT Canvas works.

c) Also, when overriding paint methods don't forget to invoke super.paint(), super.paintComponent() or you may get unexpected results.

d) However, based on the posted code there is no need to even do custom painting (since you are drawing the image at its actual size). Just create an ImageIcon from the image and add the Icon to a JLabel. Then you just add the label to the GUI.

I suggest you read the section from the Swing tutorial on How to Use Icons. If the image quality is poor then the problem is probably with your image because now you are using standard code, not custom code.

camickr
Thanks, it helped me !
rantravee