I am trying to load a resource image, but I am getting an error that says:
javax.imageio.IIOException: Can't read input file!
if(full.equals("")){
try{
full = HomePage.class.getResource("/images/default.jpg").getPath();
System.out.println(full);
File imgPath = new File(full);
BufferedImage bufferedImage = ImageIO.read(imgPath);
WritableRaster raster = bufferedImage.getRaster();
DataBufferByte data = (DataBufferByte)raster.getDataBuffer();
full = "data:image/jpeg;base64," + DatatypeConverter.printBase64Binary(data.getData());
}catch(IOException ex){
Logger.getLogger(HomePage.class.getName()).log(Level.SEVERE, null, ex);
}
}
When I print out the variable full, I get the following location:
file:/C:/Users/rnaddy/Documents/NetBeansProjects/Phantom%20Browser/dist/run1534966744/Phantom_Browser.jar!/images/default.jpg
So, what am I doing wrong?
ImageIO knows how to read from jar files, so you can just say
BufferedImage bufferedImage = ImageIO.read(HomePage.class.getResource("/images/default.jpg"));
As for why your solution doesn't work, getResource returns a URL. If you print it out when you run your application through the jar, you'll see that it returns jar:file:/path/to/file for the resource, whereas if you ran getPath and printed that out, you'll see file:/path/to/file.
Presumably, ImageIO will handle the input differently depending on what kind of URL you pass in.
Related
I'm trying to add image of user's selection to my pdf generated through pdfbox in netbeans. If i directly give path to directly then it's working but with getting url of image path and adding that doesn't work.
See the given code problem is with URL and Path, Because input isn't getting read
public static ByteArrayOutputStream PDFGenerator(........,Path imagespath)
{
........
if (finalpdf.Images != null)
{
Path imagepath = Paths.get(imagespath.toString(), "room.png");
PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath.toString(), pdf);
AddImages(content, Addedimage, 229.14f, 9.36f);
}
//AddImages method is following
public static void AddImages(PDPageContentStream content, PDImageXObject image, float x, float y) throws IOException
{
content.drawImage(image, x, y);
}
}
//Following is snippet from my test method
public void testClass()
{
........
finalpdf.Images = "room.png";
URL imageurl = testclass.class.getResource("room.png");
Path imagepath = Paths.get(imageurl.getPath().substring(1));
ByteArrayOutputStream baos = PDFGenerator.generatefurtherpdf(finalpdf, "0000.00", "00.00", imagepath);
writePDF(baos, "YourPdf.pdf");
}
I expect that it works this way but i'm sure its some problem with Path, I'm not using this correctly. I hope the code is explanatory enough as i'm quite new also there are security reasons so I can't put the whole code. Sorry for mistakes
For resources (never a File) there exists a generalized class: Path.
Path path = Paths.get(imageurl.toURI());
However whenever that path (for instance with an URL ´jar:file//... .jar!... ... .png") will be used as File, which an path.toString() suggests, one can use an InputStream.
The second generalized class is an InputStream which is more low-level:
InputStream in = TestClass.getResourceAsStream(imagepath);
This is a short-cut for the never used getResource().openStream(). Throwing a NullPointerException when the resource path is incorrect.
The last ressort is to use the actual byte[] for createFromByteArray.
byte[] bytes = Files.readAllBytes(path);
PDImageXObject Addedimage = PDImageXObject.createFromByteArray(doc, bytes, name);
Using a temporary file
Path imagepath2 = Files.createTempFile("room", ".png");
Files.copy(imagepath, imagepath2);
PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath2.toString(), pdf);
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
}
}
In my application i have a uploaded functionality.For that i have used apache-commons file upload and spring multipart and i have stored the image in directory folder(not within project context).
The problem where i stuck is fetching the image and rendering it on the jsp.I tried to read the image from that folder using Buffered image and ImageIO but can't figured out how to render it in jsp using img tag.
Any help would be appreciated.
//Code for reading
BufferedImage im=ImageIO.read(new File(imagePath));
Finally able to display the image on web browser using img tag.
Step that i follow now :
1. I read the image using BufferedImage.
2.Converted the bufferedImage into byte using ByteArrayOutputStream.
3.Encoded that stream into Base64 using apache commons codec lib and coverted into string
4.Returned this string value of image on html using img tag
//Pseudo Code
BufferedImage bufferedImage=ImageIO.read(new File(imagePath));
//imageDao contains the image name that i stored in the database
String []formatSplit=imageDao.split("\\.");
if(formatSplit.length==2){
String format=formatSplit[1];
//ImageUtility is class that contain code for converting bufferedimage to string
String traineeImage=ImageUtility.encodeToString(bufferedImage,format );
model.addAttribute("imagePath", traineeImage);
}
//ImageUtilty class -method
public static String encodeToString(BufferedImage image, String type) {
String imageString=null;
String encodedImage=null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
encodedImage=org.apache.commons.codec.binary.Base64.encodeBase64String(imageBytes);
imageString = "data:image/"+type+";base64,"+encodedImage;
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
And in the img tag src attribute i passed imageString and it worked.
For finding the solution lot of hint i found from stackoverflow and from other blog that helped me to achieve what i was looking for.
Thanks.
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();
}
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.