I am making a Java-SQL database storing app on Eclipse and MySQL. In this app, I have to upload image to the file directory. Currently while making this app, I am using an image upload path and storing all the uploaded images there. But when I'm finished with the app, and if I'm to work it on someone else's computer the image upload path in the code obviously will not work on that computer. What shall I do to make it work on other computer as well? Should I make a prompt which asks for image upload path every time the app opens and store that, or something else?? please help.
private String imageUploadPath = "/home/tsoprano/Documents/eclipse-workspace/enable/src/com/enable/regis/imgupload/";
File file1;
picLabel = new JLabel(" Upload Photo");
picLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
JFileChooser imageChooser= new JFileChooser();
if(imageChooser.showOpenDialog(picLabel)==JFileChooser.APPROVE_OPTION) {
file1 = imageChooser.getSelectedFile();
ImageIcon icon= new ImageIcon(imageChooser.getSelectedFile().getPath());
Image img=icon.getImage().getScaledInstance(130, 150, Image.SCALE_SMOOTH);
icon= new ImageIcon(img);
picLabel.setIcon(icon);
}
}
});
//inside the submit button action
String filePath = imageUploadPath + file1.getName();
try {
BufferedImage bi = ImageIO.read(file1);
ImageIO.write(bi, "jpg", new File(filePath));
} catch (IOException e1) {
e1.printStackTrace();
}
rdto.setPicUrl(filePath);
I would not suggest doing this via a config file, because this is not very user-friendly. Instead, get the current directory (i. e. the one that you executed the java command) using System.getProperty("user.dir"). Then create a new folder inside there, and use it as your upload folder. This will make sure you always have a useable path without bothering the user with specifying it.
Related
I want to add a image in JLabel that can display after building the project too in eclipse.
I have this code..
jLabel1.setIcon(new ImageIcon(getClass().getResource("/student/information/system/images/bk4.jpg")));
Goodness, why are you trying to read an image file in one line?
First, make sure that your resources folder is defined for your project and is on the build path.
Here's an example from one of my Java projects.
Next, code a method to read image files from the resources folder.
private Image getImage(String filename) {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/" + filename));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Read the image file once, saving the result in a class variable ImageIcon.
imageIcon = new ImageIcon(getImage("image.png"));
Finally, reference the ImageIcon in your Swing code.
jLabel1.setIcon(imageIcon);
This code throws a NullPointerException and I have no idea why.
try {
imageIcon = new ImageIcon(ImageIO.read(new File("res/Background.png")));
backgroundImage = imageIcon.getImage();
signIn = new MyButton("SignIn", ImageIO.read(new File("res/SignIn.png")), ImageIO.read(new File("res/SignInHover.png")));
signUp = new MyButton("SignUp", ImageIO.read(new File("res/SignUp.png")), ImageIO.read(new File("res/SignUpHover.png")));
back = new MyButton("Back", ImageIO.read(new File("res/Back.png")), ImageIO.read(new File("res/BackHover.png")));
exit = new MyButton("Exit", ImageIO.read(new File("res/Exit.png")), ImageIO.read(new File("res/ExitHover.png")));
} catch(IOException e) {
JOptionPane.showMessageDialog(null, "");
}
res/ is a source folder in the project root which contains all images used in this piece of code but I'm not able to get it to work. I've tried using getClass().getResource() (which works from inside Eclipse but not from a .jar file) and getClass().getResourceAsStream() (which throws an exception telling that the input stream is null) but to no avail.
P.S.: MyButton is a user-defined class which extends JButton and has a constructor MyButton(String, final BufferedImage, final BufferedImage).
After all I succeeded by just making images folder under my source(i.e. under res) folder. And using method
ImageIO.read(getClass().getResource("/images/SignIn.png"));
I have following code to upload an image and show it on the webpage
// Show uploaded file in this placeholder
final Embedded image = new Embedded("Uploaded Image");
image.setVisible(false);
// Implement both receiver that saves upload in a file and
// listener for successful upload
class ImageUploader implements Receiver, SucceededListener {
public File file;
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File(tmp_dir + "/" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
return null;
}
return fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
// Show the uploaded file in the image viewer
image.setVisible(true);
image.setSource(new FileResource(file));
}
};
ImageUploader receiver = new ImageUploader();
// Create the upload with a caption and set receiver later
Upload upload = new Upload("Upload Image Here", receiver);
upload.setButtonCaption("Start Upload");
upload.addSucceededListener(receiver);
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, image);
The problem is, it shows the full resolution and I want to scale (so it remains proportional) it down to 180px width. The picture also needs to be saved as the original filename_resized.jpg but I can't seem to get it to scale. Several guides on the web talk about resizing (but then the picture gets distorted) or it gives some issues with Vaadin.
Update:
Added the scarl jar (from this answer)) because it would be easy-peasy then by using following code:
BufferedImage scaledImage = Scalr.resize(image, 200);
but that gives following error:
The method resize(BufferedImage, int, BufferedImageOp...) in the type Scalr is not applicable for the arguments (Embedded, int)
and I cannot cast because Cannot cast from Embedded to BufferedImage error
Update: with following code I can cast to the right type
File imageFile = (((FileResource) (image.getSource())).getSourceFile());
BufferedImage originalImage = ImageIO.read(imageFile) ;
BufferedImage scaledImage = Scalr.resize(originalImage, 200);
but now I can't show the image..
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, scaledImage);
because of error The method addComponents(Component...) in the type AbstractComponentContainer is not applicable for the arguments (Upload, BufferedImage)
You cannot use Vaadin objects directly with a third-party tool such as Scalr without adapting one to the other. "Embedded" is a Vaadin class whereas SclaR expects a "BufferedImage".
So, you first need to extract the File object from the Embedded object:
File imageFile = ((FileResource)(image.getSource()).getSourceFile();
Then, load it into the BufferedImage using ImageIO, such as explained in the link you pointed at ( What is the best way to scale images in Java? )
BufferedImage img = ImageIO.read(...); // load image
Then, you have the BufferedImage object you were looking for.
I am developing an image editing app, so want to display an image selected by JFileChooser, so what would be best approach so that it can display all formats jpg, png, gif etc. OpenButton is used for invocation of filechooser.
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChosser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChosser.getSelectedFile();
// What to do with the file
// I want code for this part
try {
//code that might create an exception
}
catch (Exception e1) {
e.printStackTrace();
}
}
}
The easiest way is probably to create an ImageIcon from the URL of the file (or from the content of the file as bytes, or from the file name), and to wrap this ImageIcon into a JLabel:
iconLabel.setIcon(new ImageIcon(file.toURI().toURL()));
But if your app is supposed to edit the image, then you'll have to learn how to manipulate java.awt.Image instances, and the easiest way won't be sufficient.
I've done a lot of reading around SO and Google links.
I have yet to figure out how to correctly add an image into an eclipse gui project is such a way that the system will recognize find it. I know there's some mumbojumbo about CLASSPATH but it probably shouldn't be this difficult to do.
Let me start by describing what I'm doing...(If someone could correct me, it'd be appreciated.)
Here is my method.
I add the image using the "import wizard" (right click, "import", "general", "file") into an "import directory" I called "/resources"
Eclipse automatically creates a folder called "resources" in the eclipse package explorer's tree view. Right under the entry for "Referenced Libraries".
Note, "resources" isn't under "Referenced Libraries", it's at the same level in the tree.
I then use the following code:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/resources/image.jpg");
Image logo = ImageIO.read(input);
And at this point, I run the test program and get this error:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at Test.main(Test.java:17)
Thanks for any help in advance!
Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:
InputStream input = classLoader.getResourceAsStream("image.jpg");
Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
If you still have problems with Eclipse finding your files, you might try the following:
Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
Verify the default working directory by printing the following in your main:
System.out.println("Working dir: " + System.getProperty("user.dir"));
For (1) above, I put the following debugging code around the specific file I was trying to access:
File imageFile = new File(source);
System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
if (!imageFile.exists()) {
System.out.println("file " + imageFile + " does not exist");
}
image = ImageIO.read(imageFile);
For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).
Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.
It is very simple to adding an image into project and view the image.
First create a folder into in your project which can contain any type of images.
Then Right click on Project ->>Go to Build Path ->> configure Build Path ->> add Class folder ->> choose your folder (which you just created for store the images) under the project name.
class Surface extends JPanel {
private BufferedImage slate;
private BufferedImage java;
private BufferedImage pane;
private TexturePaint slatetp;
private TexturePaint javatp;
private TexturePaint panetp;
public Surface() {
loadImages();
}
private void loadImages() {
try {
slate = ImageIO.read(new File("images\\slate.png"));
java = ImageIO.read(new File("images\\java.png"));
pane = ImageIO.read(new File("images\\pane.png"));
} catch (IOException ex) {
Logger.`enter code here`getLogger(Surface.class.getName()).log(
Level.SEVERE, null, ex);
}
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));
g2d.setPaint(slatetp);
g2d.fillRect(10, 15, 90, 60);
g2d.setPaint(javatp);
g2d.fillRect(130, 15, 90, 60);
g2d.setPaint(panetp);
g2d.fillRect(250, 15, 90, 60);
g2d.dispose();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public class TexturesEx extends JFrame {
public TexturesEx() {
initUI();
}
private void initUI() {
add(new Surface());
setTitle("Textures");
setSize(360, 120);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TexturesEx ex = new TexturesEx();
ex.setVisible(true);
}
});
}
}
If you are doing it in eclipse, there are a few quick notes that if you are hovering your mouse over a class in your script, it will show a focus dialogue that says hit f2 for focus.
for computer apps, use ImageIcon. and for the path say,
ImageIcon thisImage = new ImageIcon("images/youpic.png");
specify the folder( images) then seperate with / and add the name of the pic file.
I hope this is helpful. If someone else posted it, I didn't read through. So...yea.. thought reinforcement.