Friday, February 12, 2010

Programmer - why is my image in Java application messed when it is wider? (including code to show the problem)

Programmer Question

Somehow the image is messed up when it is scaled to be relatively wider. It only happens on some machine; everything seems fine on a different machine. And it only happens for some images.



Here is the messed up display: http://www.freeimagehosting.net/uploads/35105d3017.jpg



This is when I make the window (JFrame) a little wide, so it becomes OK: http://www.freeimagehosting.net/uploads/a2580d86b1.jpg



(Note I only showed the top part of image, so the grass in the messed-up version is not in the second one)



(I had to take the images out because I didn't earn any reputation yet.)



The complete code to demonstrate this:




import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;


public class Imager {

/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
ImageComponent component = new ImageComponent("P1010013.JPG");
frame.add(component);
frame.setPreferredSize(new Dimension(300, 300));
frame.pack();
frame.setVisible(true);
}

static class ImageComponent extends JComponent {
Image img;
ImageComponent(String file) {
InputStream inputStream;
try {
inputStream = new FileInputStream(file);
img = ImageIO.read(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

protected void paintComponent(Graphics g) {
super.paintChildren(g);
// g.drawImage(img, 0, 0, 100, 100, null);
g.drawImage(img, 0, 0, 1000, 1000, null);
}

}

}

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails