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.
Related
I created an app that works with files and works perfectly in the computer where I wrote the code, however it does not work correctly in other computers. After reviewing the entire code I was able to find the issue. I removed the following method that adds an image and the jar file works fine in multiple computers, however I need the image to be added. The method is the following: (doc is a static variable declared in another class, in case you wonder)
public void AddImage() throws IOException, InvalidFormatException {
XWPFParagraph parag = document.createParagraph();
XWPFRun r = parag.createRun();
URL imageURL = ClassLoader.getSystemResource("TheImage.png");
String imageName = imageURL.getPath();
File image = new File(imageName);
FileInputStream fis = new FileInputStream(image);
BufferedImage bimg1 = ImageIO.read(image);
int width = 160;//bimg1.getWidth();
int height = 26;//bimg1.getHeight();
String imgFile = image.getName();
r.addPicture(fis, document.PICTURE_TYPE_PNG, imgFile, Units.toEMU(width), Units.toEMU(height));
}
To give you more details, I created a source file in the project in eclipse where I added the image, does anybody know how to solve this?
Perhaps on your computer the image is taken from the file system instead from the jar. Is the image packaged in the jar file? Then try
Inputstream logo = getClass().getResourceAsStream("/path/in/jar/img.png");
to load it.
How to read a file from jar in Java?
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) {
...
}
Maybe its something simple i am over looking, but i need to be able to create sub directories using a list of numbers stored in a txt file. When i use a string literal it creates the directory, but when i switch to using the variable being used for the items in the list it will not. Here is the code block.
private static void GetJarDir() throws URISyntaxException {
CodeSource codeSource = NewJFrame.class.getProtectionDomain().getCodeSource();
File jarFile = null;
jarFile = new File(codeSource.getLocation().toURI().getPath());
jarDir = jarFile.getParentFile().getPath().replace("dist", "").replace("build", "");
mainFolder = jarDir + "Invoices\\";
}
this is the method i use to get the directory for the jar file and append the path with the directory i need to create the sub-directories in, i'm sure this works.
BufferedImage dest = image.getSubimage(0, 3377, 465, 80);
String newDir = new OCR().recognizeEverything(dest);
File theDir = new File(mainFolder + newDir);
new File(mainFolder + newDir.mkdirs();
im using an optical character recognition library to grab an invoice number off of a cropped image. So newDir is the invoice number. Ive printed out the path and it is the correct path, it is just not creating the directory. If i change the variable to the actual invoice number it works, any ideas?
new File(mainFolder + "223545").mkdirs();
so sitting here playing with it ive narrowed the problem down to the string returned from the OCR. It has to be a string or it wouldnt compile...but when i try to parse the string to an int it throws an exception. and it is in fact an integer
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();
}
I don't know why this isn't working, but the program says it can't read the input file. This is also being run in Ubuntu, by the way:
Here is the sample code:
URI url = new URI("images/GUI/TitleScreen.PNG");
File file = new File(url.toString());
bg = new ImageBackground(ImageIO.read(file));
The directory is located in the bin folder and src folder of the program as well.
What if you instead got your image as a stream from a resource? e.g.,
String imgPath = "images/GUI/TitleScreen.PNG";
BufferedImage buffImage = ImageIO.read(getClass().getResourceAsStream(imgPath));
bg = new ImageBackground(buffImage);