Reputation: 67
i am using Jtree for image list and displaying the selected image, but problem is that if the image size is larger than the canvas size(i.e. 300 X 300) it displays only top left of the image, how to display the whole image in fixed size canvas?
i am using following code:
private void displayImage(File file) {
try
{
BufferedImage image = ImageIO.read(file);
ta.Picture = image;
}
catch (Exception e)
{}
Graphics g = ta.imageCanvas.getGraphics();
g.clearRect(0, 0, 300, 300);
g.drawImage(ta.Picture, 00, 00, this);
} // displayImage
public void valueChanged(TreeSelectionEvent e)
{
// TODO Auto-generated method stub
FileTreeNode node = (FileTreeNode) tree.getLastSelectedPathComponent();
if (node.isLeaf())
{
currentFile = node.file;
File ff = new File("F:/images_blue/" + currentFile.getName());
displayImage(ff);
} else
currentFile = null;
}
Upvotes: 1
Views: 1001
Reputation: 347234
I'd just like to point out that...
Graphics g = ta.imageCanvas.getGraphics();
g.clearRect(0, 0, 300, 300);
g.drawImage(ta.Picture, 00, 00, this);
Is a really bad idea.
getGraphics
may return null
and is, at best, simply a snapshot of the last repaint cycle and could be invalidated or dereferenced on the next paint cycle.
You should be extending from something like JPanel
and overriding the paintComponent
method. This would allow you to supply a getter and setter as apart of the image management and allow you to produce the scaled image in a self contained and reusable manner
You check out Perfoming Custom Painting for me information
And, as per my comment, you might like to check out these previous questions for examples
Upvotes: 2
Reputation: 304
you can scale BufferedImage like this..
BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
AffineTransformOp scaleOp =
new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);
Upvotes: 1