I'm trying to get the Thumbnail that is associated to a particular file, and then resize it. I've been testing on Mac, and haven't been able to find a solution that would allow me to achieve this.
Code so far:
import com.apple.laf.AquaIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class TestSystemIcon extends JFrame
{
JPanel panel;
ImageIcon icon;
public TestSystemIcon()
{
panel = new JPanel();
JButton button = new JButton("Open...");
final JLabel label = new JLabel();
icon = null;
final JPanel en = new JPanel(new FlowLayout(FlowLayout.CENTER));
label.setHorizontalAlignment(SwingConstants.CENTER);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(null) == JFileChooser.OPEN_DIALOG)
{
File file = fileChooser.getSelectedFile();
icon = resizeIcon(getThumbnail1(file),200,200);
// icon = resizeIcon(getThumbnail2(file),200,200);
System.out.println(icon);
label.setIcon(icon);
en.add(label);
revalidate();
repaint();
}
}
});
panel.add(button);
this.add(panel,BorderLayout.NORTH);
this.add(en,BorderLayout.CENTER);
this.setSize(400,400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public ImageIcon getThumbnail1(File file)
{
JFileChooser f = new JFileChooser();
Icon i = f.getIcon(file);
//Mac Conversion.
Image image = AquaIcon.getImageForIcon(i);
return new ImageIcon(image);
}
public ImageIcon getThumbnail2(File file)
{
return new ImageIcon(file.getPath());
}
public ImageIcon resizeIcon(ImageIcon imageIcon,int width, int height)
{
return new ImageIcon(imageIcon.getImage().getScaledInstance(width,height,Image.SCALE_SMOOTH));
}
public static void main(String[] args)
{
TestSystemIcon test = new TestSystemIcon();
test.setVisible(true);
}
}
Version1 of getting the thumbnail has following behaviour:
Can open thumbnails
Very small, scaling not suitable.
Version2 of getting thumbnail has following behaviour:
Doesn't display image, despite finding image (System.out proves this).
Except for pdf, where instead it displays the actual file, as opposed to the
thumbnail
When it does work i.e. pdf, it scales nicely.
I know I can use sun.awt.shell.ShellFolder;, however I am aiming for a cross-platform solution.
Thanks for any help
I looked at some code that I have done in the past and seems this works fine when you use JLabel with and ImageIcon, try this code that resized a large image to 100x100,
ImageIcon icon = new ImageIcon("Penguins.jpg");
Image img = icon.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
// if the file is not an image, but a file on the system,
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
Image img = ((ImageIcon) icon).getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon1 = new ImageIcon(img);
JLabel image = new JLabel(icon1);
Related
Well, the only problem I am having is that the open dialog is showing first. What I want is to only to put it inside the JFrame and then do the rest inside the JFrame like opening image and display it. It should be like this
The problem is that my JFileChooser is showing first. And also the thing is I want it all to be inside the JFrame just like in the image shown.
Here is my code:
import java.awt.Image;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.border.*;
import java.awt.Color;
import java.awt.Dimension;
public class imgviewer extends JFrame{
JButton button;
JLabel label;
public imgviewer() {
super("Image viewer");
label = new JLabel();
label.setBounds(400, 10, 180, 300);
Border b = BorderFactory.createLineBorder(Color.ORANGE, 2);
JFileChooser file = new JFileChooser(".");
label.setBorder(b);
add(label);
file.setPreferredSize(new Dimension(400, 300));
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg", "png", "gif");
file.addChoosableFileFilter(filter);
int result = file.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
label.setIcon(ResizeImage(path));
}
else if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("No File Selected");
}
add(file);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(600, 350);
setVisible(true);
}
public ImageIcon ResizeImage(String ImagePath) {
ImageIcon MyImage = new ImageIcon(ImagePath);
Image img = MyImage.getImage();
Image newImg = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImg);
return image;
}
public static void main(String[] args) {
new imgviewer();
}
}
I'm not sure how to do what you want to do, but where you put the line int result = file.showOpenDialog(null); into your code, that's a line that explicitly means "open this JFileChooser in its own file dialog NOW". In the order of your code, that clearly happens before the setVisible(true) line which would open the wrapper you wish to put around the file dialog.
Is there a reason the code after file.addChoosableFileFilter(filter);, and before add(file), is indented? If you were imagining that this code is in a separate block which will prevent it from being executed until later, it isn't.
I haven't worked with JFileChooser, or Swing in general, for a long time now, so I don't know off hand how well a JFileChooser will work if treated as a separate component embedded inside another component, but if that's going to work at all, you definitely cannot use JFileChooser's showOpenDialog method.
My question is about Image not appearing when jlabel is clicked from menu
Why does the image does not appear when I click from menu? Please help. Newbie here
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Lab05Part02 extends JFrame implements ActionListener{
JMenuItem b1,b2,b3;
JLabel bankImg;
ImageIcon img1 = new ImageIcon("aib.jpg");
ImageIcon img2 = new ImageIcon("BOI.jpg");
ImageIcon img3 = new ImageIcon("kbc.jpeg");
Lab05Part02(){
JMenuBar mb = new JMenuBar();
JMenu banks = new JMenu("Banks", false);
banks.add(b1 = new JMenuItem("AIB"));
b1.addActionListener(this);
banks.add(b2 = new JMenuItem("Bank of Ireland"));
b2.addActionListener(this);
banks.add(b3 = new JMenuItem("KBC"));
b3.addActionListener(this);
mb.add(banks);
setJMenuBar(mb);
JPanel p = new JPanel();
bankImg = new JLabel();
p.add(bankImg);
getContentPane().add(p);
setSize(500,500);
setVisible(true);
}//end of constructor
public static void main(String[] args){
Lab05Part02 myMenu = new Lab05Part02();
}//end of main method
public void actionPerformed(ActionEvent e){
Object source = new Object();
if(source == b1){
bankImg.setIcon(img1);
}
else if(source == b2){
bankImg.setIcon(img2);
}
else if(source == b3){
bankImg.setIcon(img3);
}
else{
bankImg.setText("Select Image from Menu");
}
}//end of listener method
}//end of class
Where did I go wrong? On else if statements? Can someone explain this to me? I did putting setVisible(true) on every condition but it did not work. Thank you in advance!
In the actionPerformed method you forgot to get the source object from the ActionEvent e and you just created a new object:
Object source = new Object();
As it's obvious, in this way source is not equals to the reference of one of your buttons.
The ActionEvent object contains the source of event. In order to resolve the issue get the source object from ActionEvent e argument:
Object source = e.getSource();
If your images ("aib.jpg", "BOI.jpg" and "kbc.jpeg") are in a right path and your ImageIcon img1, img2, img3 objects populated successfully you are good to go with the above fix.
But I can advise that if you want no further inconvenience for showing images and icons in your project, it's better you put them under a package like resources.images and also create a java class there and name it Resources.java for example.
Then you can create images using the resource stream of Resources.java which is in the same package with images and icons:
package resources.images;
import java.net.URL;
import javax.swing.ImageIcon;
public class Resources {
public static ImageIcon getImageIcon(String name) {
URL imagePath = Resources.class.getResource(name);
return new ImageIcon(imagePath);
}
}
Then in your code you can write
ImageIcon img1 = Resources.getImageIcon("aib.jpg");
instead of
ImageIcon img1 = new ImageIcon("aib.jpg");
This way it will work even if you package your application as a jar file.
Hope this helps.
This question already has answers here:
Select an area to capture using the mouse
(2 answers)
Closed 8 years ago.
In my Java code, I am trying to browse an Image from my directory and then am trying to access to that selected image and capture an area (sub Image) from my image. I have some problems that once I select the image, I do not have access to the image (ImageIcon or BufferedImage). Because, I need its information to get a subimage out of it.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class selectWindow extends JFrame{
// In this GUI project we need just one JPanel inside the JFrame
private JPanel imagePanel;
private JPanel buttonPanel;
private JButton selectImage;
private JLabel imageLabel;
File targetFile;
private ImageIcon image;
static BufferedImage targetImg;
private static final String basePath = "C:\\Users\\mroozbahani3\\Desktop";
private static final int baseSizeX = 900-110;
private static final int baseSizeY = 660;
Rectangle captureRect;
File file;
// Now let's make the constructor
public selectWindow(){
// The below code will close the window(JFrame), once we have click on window exit
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//lets define the default size of our window page(main JFrame), where the first value is the x and second one is y;
setSize(900,660);
selectImage = new JButton("Select Image");
selectImage.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
image = selectButtonActionPerformed(e);
}
});
imagePanel = new JPanel();
imageLabel = new JLabel(image);
imagePanel.add(imageLabel);
// The below part is for JPanel related to the buttons
buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints grid = new GridBagConstraints();
grid.insets = new Insets(10,10,10,10);
// Select Buttom
grid.gridx = 0;
grid.gridy = 1;
buttonPanel.add(selectImage,grid);
// We can determine that how much of the space is going to be belonged to adjustPanel
buttonPanel.setPreferredSize(new Dimension(110,660));
setLayout(new BorderLayout());
add(buttonPanel,BorderLayout.WEST);
add(imagePanel,BorderLayout.EAST);
setResizable( false );
}
private ImageIcon selectButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new ImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
targetImg = rescale(ImageIO.read(file));
return new ImageIcon(targetImg);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
return new ImageIcon(targetImg);
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSizeX, baseSizeY, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSizeX, baseSizeY, null);
g.dispose();
return resizedImage;
}
public static void main(String[] args) throws AWTException{
JFrame gui = new selectWindow();
gui.setVisible(true);
}
}
You can create a new Image based on your selection rectangle.
See Screen Image for a simple way to do this.
I'm trying to add an image to one frame but it seems it does not working. The image created by an ImageIcon from the specified file. The image file is in the seam directory the java file exist.
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class image {
public static void main(String args[])
{
TimeFrame frame = new TimeFrame();
}
}
class TimeFrame extends JFrame
{
//Image icon = Toolkit.getDefaultToolkit().getImage("me.jpg");
ImageIcon icon = new ImageIcon("me.jpg");
JLabel label = new JLabel(icon);
public TimeFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("My Frame");
setSize(500,400);
//this.setIconImage(icon);
add(label,BorderLayout.CENTER);
setVisible(true);
}
}
If your icon is beside the TimeFrame java file, you should use
java.net.URL imgUrl = getClass().getResource("me.jpg");
ImageIcon icon = new ImageIcon(imgUrl);
or
java.net.URL imgUrl = TimeFrame.class.getResource("me.jpg");
ImageIcon icon = new ImageIcon(imgUrl);
You are (probably) currently looking for it in your working directory which you can output via
System.out.println(System.getProperty("user.dir"));
Will u try this one?
ImageIcon ImageIcon = new ImageIcon("me.jpg");
Image Image = ImageIcon.getImage();
this.setIconImage(Image);
Simply change the directory to "src/me.jpg"
i try to make imageviewer, the code is below
import javax.swing.*;
import java.awt.event.*;
import java.IO.*;
public class javaImageViewer extends JFrame{
public javaImageViewer(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(200,100);
JButton openButton = new JButton("Open Images");
getContentPane().add(openButton);
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser(".");
int status = chooser.showOpenDialog(javaImageViewer.this);
if(status == JFileChooser.APPROVE_OPTION){
try{
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(chooser.getSelectedFile().toURL()));
frame.add(label);
frame.setSize(500,500);
frame.setVisible(true);
}
catch(Exception e2){
System.out.println("Error"+e2);
}
}
}
});
}
public static void main(String [] args){
javaImageViewer tim = new javaImageViewer();
tim.setVisible(true);
}
}
but when i open image from camera, it always showing over the frame size
i dont know how to make the image follow my frame size ?
in order to place your image with the Full Size, you can try to make your own JPanel, override the paintComponent method, and inside this method use g.DrawImage ,
other solution and maybe easier is set the JPanel dimesion with the same dimesion of you Image and Add this JPanel to a JScrollPane , in this way is going to show a scrollbars to navigate
depends of reall size in pixels
1) put Image / BufferedImage as Icon/ImageIcon to the JLabel, then image will be resiziable up to real size in pixels
2) resize Image by usage of Image#getScaledInstance(int width, int height, int hints)