how to get path of specific bufferedimage? - java

Hi I am trying to get path of BufferedImage but how to get path of that loaded image i don't know.
I am fetching image from Stack<>. one by one image fetched from it when user click on next button.
image changed using pop() method of stack.
code :
Stack<File> pictures ;
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(panel);
String path = file.getSelectedFile().getAbsolutePath();
System.out.println(path);
pictures= getFilesInFolder(path.toString());
a=ImageIO.read(pictures.pop().getAbsoluteFile());
here a is Buffered Image instance.
now i want whole path of image that loaded in a.
anyone guide me ?

A BufferedImage does not maintain any information on how it is generated or where it is loaded from. You have to store the file path in a variable before loading the image:
File file = pictures.pop().getAbsoluteFile();
a=ImageIO.read(file);
// now you can use "file" for other purposes too

The Problem is that you have is that you can't read a Path from a BufferedImage so you have to use the File before you make a BufferedImage of it.
So you could use:
String path = stack.peek().getPath();
Now you have saved your path. At the moment you convert it into a BufferedImage use pop() so you remove it from the stack. With peek() you only look at the first Item without removing. Or you save your file into a temp file like
File temp = stack.pop();
Than you are able to use:
temp.getPath();

yes i have solve that using following code :
String p;
File f;
try
{
f= pictures.pop().getAbsoluteFile();
a=ImageIO.read(f);
p = f.getPath();
System.out.println(p);
}
catch (IOException e1)
{
e1.printStackTrace();
}

Related

Wrong filepath in java

So we got this assignment in a basic java programming course and we're supposed to implement a kind of card deck. To help us with this they have given us resources that will present a GUI on the screen, but when running my program I get a IOException that says that it can't read the input file, most likely since the pathname is wrong. And I dont know how to fix it, we're not even supposed to be in meddling with this code. The error is thrown in this method:
private Image getImg(Card aCard) {
File pathToFile = null;
if (aCard == null) {
pathToFile = new File("cardset-oxymoron/shade.gif");
} else {
String suits = "cdhs";
char c = suits.charAt(aCard.getSuit());
String fileName = String.format("%s/%02d%c.gif", "cardset-oxymoron", aCard.getRank(), c);
pathToFile = new File(fileName);
}
Image img = null;
try {
img = ImageIO.read(pathToFile);
} catch (IOException ex) {
System.err.println("Failed to create image");
ex.printStackTrace();
}
return img;
}
And according to the error stack(?) it is at line 99, which is the
img = ImageIO.read(pathToFile);
line
The folder that the cards are in is inside the project folder, right in between bin and src. using IntelliJ debugger I can see that the the pathToFile is "cardset-oxymoron\02d.gif". The filename is correct as all the cards are "[01-13][c/d/h/s].gif". When I rightclicked and copied the path to the files inside IntelliJ it was using forwardsslashes and not backslashes. But then I checked in explorer and it was the other way around... I have no idea where this is going wrong, any input would be greatly appreciated!
According to your code your files are in directory cardset-oxymoron relative to your JVM run directory. I'm not sure about IntelliJ (I work all the time with Eclipse and Maven), but it could be bin directory.
You can check it by put those 2 lines to see what is it actually (somewhere before your actual code)
File currentDir = new File("./");
System.out.println(currentDir.getAbsolutePath());
Then your cardset-oxymoron must be in that directory. Or you can change file path appropriately.
E.g. if currentDir is bin then pathToFile will be
pathToFile = new File("../cardset-oxymoron/shade.gif");
as well as fileName for other case.

Unable to save the uploaded file into specific directory

I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}

How to create a JavaFX Image from an absolute path?

I have an instantiated File object. I know it contains a picture format. I don't know where on the system the file is placed, other than the methods of File available to me getPath(), getAbsolutePath() etc.
My question is: how can I instantiate a JavaFX Image object with the picture in my File?
File provides a method to retrieve the URL for the file and the Image constructor expects a URL String.
Image imageForFile = new Image(file.toURI().toURL().toExternalForm());
Combining the javax.imageio.ImageIO class (ref) and the javafx.embed.swing.SwingFXUtils (ref) can convert an "input" (i.e.: stream, file, URL) to a JavaFX image. Sample code (for File):
public static Image readImage(File file) {
try {
BufferedImage bimg = ImageIO.read(file);
return SwingFXUtils.toFXImage(bimg, null);
}
catch( IOException e ) {
// do something, probably throw some kind of RuntimeException
}
}

Image in loading from specified path

When I am giving absolute path of image means from my project scr directory it loads the image but when I am trying to load image from specified path or relative path then it shows null error, it doesn't read image.
i have get path using JFilechooser directory specifically, it only display .jpg image and give list of files to File type and stored one by one image in string variable and then want to load image using that variable.
My code:
final String fpath;
final File dir = new File("");
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(contentPane);
final File[] lofFile = file.getCurrentDirectory().listFiles();
for (int i = 0; i < a; i++) {
if (lofFile[i].toString().substring(lofFile[i].toString().lastIndexOf(".") + 1).equals("jpg")) {
az = lofFile[i].toString();
}
}
private BufferedImage bg;
bg = ImageIO.read(getClass().getResource(az));
Throws this exception:
java.lang.IllegalArgumentException: input == null! at javax.imageio.ImageIO.read(Unknown Source)
Any help please?
Class#getResource is not for loading files from the file system. Maybe ImageIO.read(az) will work.
But you get a File object from the JFileChooser. Use it and you have no problem at all. Don't do any String manipulation on filenames if there is no reason for it. Filtering for a specific suffix is not a reason.

ImageIO can't read input file

public static void imRes(String pat) {
try {
BufferedImage bckimg = ImageIO.read(new File("c:/s/deneme.jpg"));
File s = new File(pat);
BufferedImage im = ImageIO.read(s);
BufferedImage im1 = resIm(im);
BufferedImage finIm = mergIm(im1, bckimg);
ImageIO.write(finIm, "jpg", new File("c:/s/deneme1.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
This is my first post, excuse me if I've done something wrong. This code was running properly untill i try to read an image from the source package. But now it can't read any image. What am I doing wrong? Or is it something about eclipse?
Exception:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at imRe.imRes(imRe.java:12)
at imReTest.main(imReTest.java:6)
Thanks...
Change / for \ if you are using windows.
A more cross-platform approach would be substitute
C: for File.listRoots()[0] and every / for File.separator.
Read more on the File api documentation
EDIT
(I didn't read this line, sorry)
This code was running properly untill i try to read an image from the source package
In order to get a file from inside your jar package, one must use the getClass().getResource() method.
Example:
application-package:
|-Main.java
|-resources
|-image.jpg
For the above directory structure:
BufferedImage im = ImageIO.read(new File(getClass().getResource("/resources/image.jpg").toURI()));
Would do the trick.

Categories

Resources