Upload image to server from Java - java

Follow a small Java code to select an image from a folder. What I would like is to know how to upload it to a server, I have always uploaded images from javascript or jquery or php too. Use a AngularJS frameworks and also to upload images Ionic from mobile devices to my server, I am now working directly in Java and have some doubts. On issues of time, I would like to know how is the best way to upload an image, bits or base64? And if they could help me with this conversion would appreciate. I'm new to Java and I'm just practicing. Regards!
My code :
public class UI extends JFrame {
JButton buttonBrowse;
JButton buttonUpload;
JLabel label;
public UI(){
super("Set Picture Into A JLabel Using JFileChooser In Java");
buttonBrowse = new JButton("Browse");
buttonUpload = new JButton("Upload");
buttonBrowse.setBounds(300,300,100,40);
buttonUpload.setBounds(400, 300, 100, 40);
label = new JLabel();
label.setBounds(10,10,670,250);
add(buttonBrowse);
add(buttonUpload);
add(label);
buttonBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
//filter the files
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
//if the user click on save in Jfilechooser
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
System.out.println(path);
label.setIcon(ResizeImage(path));
}
//if the user click on save in Jfilechooser
else if(result == JFileChooser.CANCEL_OPTION){
System.out.println("No File Select");
}
}
});
buttonUpload.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(700,400);
setVisible(true);
}
// Methode to resize imageIcon with the same size of a Jlabel
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 UI();
}
}

Related

Images doesn't work in eclipse

I already did search on youtube and here and probably it is silly question but I couldn't find how to make it work.
Question is when I add pictures in my eclipse file they look like;
setLayout(new FlowLayout());
image1 = new ImageIcon(getClass().getResource("view.jpg"));
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("view1.jpg"));
label1 = new JLabel(image2);
add(label2); // here my code
Any ideas?
My got a use method to set icon for label, you can refer
private void loadAvartar(JLabel lbl, String path){
try {
BufferedImage image = ImageIO.read(new File(path));
ImageIcon icon = new ImageIcon(image.getScaledInstance(100, 100, 50));
lbl.setIcon(icon);
} catch (IOException | java.lang.NullPointerException e) {
lbl.setText("Failed");
}
}

How to draw image using FileDialog in Java

Need to display selected in FileDialog image, but thats somewhy didnt work. When i try to choose image it throws exception javax.imageio.IIOException: Can't create an ImageInputStream!
I think problem is in getDirectory() , but dont know how to fix.
public ImageShow() throws IOException {
super("Pictures");
setSize(1024,768);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonOpen = new JButton("Open file");
buttonPanel.add(buttonOpen);
actions();
fileDialog();
add(buttonPanel);
image = ImageIO.read(new File(fd.getDirectory()));
imageLabel = new JLabel(new ImageIcon(image));
buttonPanel.add(imageLabel);
}
public void fileDialog() {
fd = new FileDialog(new JFrame(), "Choose file");
fd.setVisible(true);
}
public void actions() {
buttonOpen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fileDialog();
}
});
}
}
image = ImageIO.read(new File(fd.getDirectory()));
A directory is not an image! Try instead getFile() which:
Gets the selected file of this file dialog. If the user selected CANCEL, the returned file is null.
But as I said in comments..
Use the Swing based JFileChooser rather than the AWT based FileDialog.
And be sure to consult the avialable documentation when using methods.

How does this update a component without using an actionListener?

Code in Question
There isn't an actionListener for the image thumbnails, yet when clicked they update the image.
From this webpage.
Edit: I am currently importing images using JFileChooser and then creating a thumbnail and displaying the full image in a similar way to this, although not using ImageIcons. But would like to use this method so when I add an image it adds to the list and allows me to click the thumbnail to show that image.
However mine using actionListeners to change when something is pressed but this doesn't and can't understand the code where it does.
Thanks
Edit2:
Regarding the repaint option:
I have a class which extends component which then calls a repaint function.
public class Image extends Component {
private BufferedImage img;
//Print Image
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
I then have a class with all my Swing components which call methods from other classes.
Image importedImage = new Image(loadimageone.openFile());
Image scaledImage = new Image();
// Save image in Buffered Image array
images.add(importedImage.getImg());
// Display image
imagePanel.removeAll();
imagePanel.add(importedImage);
imagePanel.revalidate();
imagePanel.repaint();
previewPanel.add(scaledImage);
previewPanel.revalidate();
previewPanel.repaint();
If I remove the revalidate or repaint it wont' update the image on the screen.
Edit 3:
This is the code on how I implemented the dynamic buttons:
//Create thumbnail
private void createThumbnail(ImpImage image){
Algorithms a = new Algorithms();
ImpImage thumb = new ImpImage();
//Create Thumbnail
thumb.setImg(a.shrinkImage(image.getImg(), 75, 75));
//Create ImageIcon
ImageIcon icon = new ImageIcon(thumb.getImg());
//Create JButton
JButton iconButton = new JButton(icon);
//Create ActionListener
iconButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bottomBarLabel.setText("Clicked");
imagePanel.removeAll();
imagePanel.add(images.get(position)); //Needs Fixing
imagePanel.revalidate();
}
});
//Add to previewPanel
previewPanel.add(iconButton);
previewPanel.revalidate();
previewPanel.repaint();
}
It looks like it uses ThumbnailAction instead which extends AbstractAction (at the very bottom of the code). Swing components can use Actions instead of ActionListeners. The advantage of Actions is that buttons can share an Action and they will automatically use the same key-bindings etc.
http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
EDIT: I have added some code demonstrating that you do not need to explicitly repaint(). Give it a try.
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(2, 1));
final JLabel iconLabel = new JLabel();
JButton button = new JButton("Put Image");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
iconLabel.setIcon(new ImageIcon(ImageIO.read(fc.getSelectedFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
panel.add(iconLabel);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
EDIT 2 (There is no Edit 2)
EDIT 3: Try this
public class MyActionListener implements ActionListener {
private JPanel imagePanel;
private Image image;
public MyActionListener(JPanel imagePanel, Image image) {
this.imagePanel = imagePanel;
this.image = image;
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Clicked");
imagePanel.removeAll();
imagePanel.add(image); //Needs Fixing
imagePanel.revalidate();
}
}

How to load an image to a JButton in java?

I want to load an image to a JButton in a java application so when I click the button to show the image and when I click it again to hide the image.I don't want the image to be loaded to a label but on the button.
I'm thinking in SWT, but I guess this works for Swing too.
final JButton button = new JButton();
final ImageIcon icon = new ImageIcon(image);
button.setIcon(icon);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setIcon( button.getIcon() == null ? icon : null );
}
});
You can try this:
ImageIcon iconStart = new ImageIcon("start.jpg");
JButton bttnStart = new JButton(iconStart);

troubles with displaying image in window

I need to choose image with file open dialog and then show it in window. But When I choose image it is not shown in the window.
I've created class which create window with jmenubar and 1 jmenuitem. When I click on menuitem JfileChooser appears and then I choose some file. But then happens nothing.
I think the problem is in actionListener for JFileChooser(ImageFilter is a filter from docs java)
public Frame(){
//create bars and window
mainframe = new JFrame("Window");
mainframe.setVisible(true);
mainframe.setSize(300, 300);
menubar = new JMenuBar();
mainer = new JMenu("Menu");
menubar.add(mainer);
//create items
item = new JMenuItem("Open",KeyEvent.VK_T);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
item.getAccessibleContext().setAccessibleDescription("open image");
//action listener
item.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//open file dialog
choser = new JFileChooser();
choser.addChoosableFileFilter(new ImageFilter());
final int returnval = choser.showOpenDialog(menubar);
//action listener for JFileChooser
choser.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (returnval == JFileChooser.APPROVE_OPTION){
fc = choser.getSelectedFile();
try{
Panel panel = new ShowImage(fc.getName());
mainframe.getContentPane().add(panel);
}catch(Exception exc){};
}
}
}
);
}
}
);
mainer.add(item);
mainframe.setJMenuBar(menubar);
}
ShowImage class
class ShowImage extends Panel{
BufferedImage image;
public ShowImage(String imagename) throws IOException {
File input = new File(imagename);
image = ImageIO.read(input);
}
public void paint(Graphics g){
g.drawImage(image,0,0,image.getWidth(),image.getHeight(),null);
}
}
P.S another problem is that it shows nothing until I change size of the window.
Extend JPanel instead of Panel, and override paintComponent method, ie:
class ShowImage extends JPanel{
public void paintComponent(Graphics g){
...
}
}
Also, there is no need to addActionListener on JFileChooser, just check the return value and act accordingly, ie:
final int returnval = choser.showOpenDialog(menubar);
if (returnval == JFileChooser.APPROVE_OPTION){
...
}
Im pretty sure this line will cause problems:
Panel panel = new ShowImage(fc.getName());
getName() will return the name of the file. So for example if you choose a image with JFileChooser named image.jpg, getName will return "image.jpg". This will make the image only show if the file you select is stored in the root folder of your project. I would change getName() to getAbsoultePath() which will return the full patch (e.i c:\desktop\image.jpg) which is most likley what you want.
Also as Max points out, you should override paintComponent rather then paint:
protected void paintComponent(Graphics g){
g.drawImage(image,0,0,image.getWidth(),image.getHeight(),null);
}

Categories