Saving a picture into a variable - java

I'm wanting to upload a picture and save it under a variable named contactPicture. I have tried looking online but can't find much, and what I have found seems to give errors. This is what i have so far.
Bitmap contactPicture = null; (Error 1)
JButton pictureanswer = new JButton("Browse");
pictureanswer.setForeground(Color.black);
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 9;
addPanel.add(pictureanswer,c);
pictureanswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
File pictureDirectory = chooser.getSelectedFile();
contactPicture = BitmapFactory.decodeFile(pictureDirectory); (Error 2)
}
});
To explain whats happening here, I create a button "Browse". This then, when clicked, opens up the browse window to search for images. It saves this file directory under the variable, pictureDirectory.
This is the bit giving errors. I found that the final line of code should save the picture. However its giving errors.
Error 1: Bitmap cannot be reserved to a type.
Error 2: BitmapFactory cannot be reserved and error 1 again.
Please explain what Im doing wrong, all help appreciated! :)

You can jsut use something like:
java.awt.image.BufferedImage img = ImageIO.read(new FileInputStream(path));

Related

Display image on a Java button

xstButton.setIcon(new ImageIcon("D://icon-tender-check-press.png"));
I am using this line of code to display an image on a Java button.
I cannot see the desired image on the button, need help!!!
You could try it like this:
Image image = ImageIO.read(getClass().getResource("D://icon-tender-check-press.png"));
button.setIcon(new ImageIcon(image));
But i would suggest to create a Folder in your project to store images:
Image image = ImageIO.read(getClass().getResource("images/icon-tender-check-press.png"));
button.setIcon(new ImageIcon(image));
Although i am not exactly sure what your question is
Probably file "D://icon-tender-check-press.png" doesn't exists or is not a valid image.
Check it exists first.
File f = new File("D://icon-tender-check-press.png");
if(f.exists() && !f.isDirectory()) {
System.out.println("File exists");
}

Java - Custom Image in JoptionPane.ShowConfirmDialog is not working

When the User enters the password and click on Ok button the password will be encrypted and stored in JTextArea. And this is working fine. But I want to add a custom logo in the showConfirmDialog and showMessageDialog popup. I tried with the below code, but the custom Image (logo) is not displaying in the message popup
public static void main(String[] args) {
Box box = Box.createHorizontalBox();
JLabel label = new JLabel("Enter your password : ");
box.add(label);
JPasswordField passwordField = new JPasswordField(24);
box.add(passwordField);
final ImageIcon icon = new ImageIcon("C:\\Users\\Test\\Internet.png");
int button = JOptionPane.showConfirmDialog(null, box, "Enter your password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.NO_OPTION, icon);
if (button == JOptionPane.OK_OPTION) {
String password = new String(passwordField.getPassword());
String encryptedPassword;
if (password != null && !password.equals("")) {
byte[] bytesEncoded = Base64.encodeBase64(password.getBytes());
JTextArea richTextField = new JTextArea(10, 10);
encryptedPassword = new String(bytesEncoded);
richTextField.setText(encryptedPassword);
richTextField.setOpaque(false);
richTextField.setEditable(false);
JOptionPane.showMessageDialog(null, richTextField);
} else {
JOptionPane.showMessageDialog(null,
"Password cannot be null. Please enter password to encrypt.");
}
}
}<br>
I'm passing ImageIcon object into the JoptionPane.showConfirmDialog as an argument. But when I run this, i don't see any Image displayed in the popup. I'm not sure what I'm doing wrong here.
Note : I need a custom Image to be displayed in both the popup's. showConfirmDialog and showMessageDialog
Any help would be greatly appreciated
Your code is perfectly fine. I just ran it in my environment and it worked fine. Which leads me to believe that your problem is the path of the image. I even tested it with a path for a image that wasn't there and the window show without showing any image.
I only changed two things, the path of the image obviously:
final ImageIcon icon = new ImageIcon("c:\\temp\\poke-ball-png-13_30x30.png");
This image I got from Free Icons PNG
And the Base64 class since there is no mention from where you are using it I use the java one:
import java.util.Base64;
....
byte[] bytesEncoded = Base64.getEncoder().encode(password.getBytes());
So be sure that your image "C:\\Users\\Test\\Internet.png" Is really there on the disk at that path

Image IO Write not writing

basically I am trying to save an image I have edited in a JFrame, so I have a menu with the save item and I have an action listener to set up for the save item and everything works fine, the file chooser comes up and I can select where I would like to save it, only thing is when I hit save, its not there. Here is my code, am I missing something?
if(e.getSource().equals(Save)){
JFileChooser keep = new JFileChooser();
keep.setSelectedFile(new File ("newImage.jpg"));
FileNameExtensionFilter filters = new FileNameExtensionFilter("jpeg", "jpg");
keep.setFileFilter(filters);
File output = keep.getSelectedFile();
int count = keep.showSaveDialog(keep);
BufferedImage out = filteredImage;
if (count == JFileChooser.CANCEL_OPTION){
}
else{
try{
ImageIO.write(out, "jpg", output);
//I put this here to see if I was even reaching the method
System.out.println("writing method");
}catch(Exception d){
}
}
}
So, you get a reference to the selectedFile...
File output = keep.getSelectedFile();
The you show the dialog...
int count = keep.showSaveDialog(keep);
BufferedImage out = filteredImage;
Then you try and save the image...
ImageIO.write(out, "jpg", output);
...wait, what?! Assuming that getSelectedFile isn't null, how do you know where you're actually saving the image?
That process should be reversed slightly...
showSaveDialog
if (accepted) {
saveFile = getSelectedFile
ImageIO.write(img, "jpg", saveFile);
}
as a basic psudo code example

java jLabel image does not update

I'm creating a feedback label that displays the picture that the user has chosen in a file dialog.
The moment when a picture file is selected, the label will update itself into that image of which the user has clicked.
The first time when the picture is chosen it works fine, however when another picture is chosen for the 2nd time onwards, it remains as the first picture.
Codes:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//browse button
FileDialog fd = new FileDialog(this, "Choose a file", FileDialog.LOAD);
fd.setDirectory("C:\\");
fd.setFile("*.jpg"); // jpg files only
fd.setVisible(true);
String filename = fd.getFile();
if (filename == null) {
System.out.println("You cancelled the choice");
} else {
savePicture("temp"); // save it in temp.jpg. This overwrites any existing picture.
ImageIcon imgThisImg = null;
imgThisImg = new ImageIcon(absfilePath+ "/temp.jpg");
jLabel7.setIcon(null);
jLabel7.setIcon(imgThisImg);
jLabel7.revalidate();
jLabel7.repaint();
}
During debugging, the moment after savePicture() function is executed, the directory picture is updated. Therefore it's not an issue with overwritting the file. The file is overwritten correctly, why does it still display the previous image? Is there a cache or something that i need to clear?
Thanks.
Using ImageIO to the read file works best. Can be achieved using the following line.
jLabel7.setIcon(new JLabel(new ImageIcon(ImageIO.read(new File("C:\\Users\\Cameron Gillespie\\Documents\\NetBeansProjects\\OnlineCabsClient\\src\\images\\taxiBackground.png")))));
You are taking the label then setting the icon. Creating a new label and ImageIcon. Then using ImageIO to read the file. Reading the image and printing it to the label.

Write result image using jmagick

I want to crop part of the image and then write the result to another image file. My code looks like this
ImageInfo imageInfo = new ImageInfo("file path");
MagickImage image = new MagickImage(imageInfo );
Rectangle cropInfo = new Rectangle();
cropInfo.x = 20;
cropInfo.y = 20;
cropInfo.width = 300;
cropInfo.height = 300;
MagickImage result = image.cropImage(cropInfo);
result.setFileName("path to result file");
boolean s = result.writeImage(imageInfo);
The above code just works but why writeImage using the old ImageInfo? and the MagickImage.setFileName don't make sense to me. I think we should create a new ImageInfo object and then write to that ImageInfo. The following code make more sense but don't work as expected.
MagickImage result = image.cropImage(cropInfo);
ImageInfo resulInfo = new ImageInfo("path to new file");
boolean s = result.writeImage(imageInfo);
Does anyone experience with this ?
It was inconvenient for me to keep the original ImageInfo around, so I tried this and it also worked:
result.setFileName("path to result file");
boolean s = result.writeImage(new ImageInfo());
As to why the parameter is needed at all, the mystery remains. Null will not work.

Categories