How to create a JavaFX Image from an absolute path? - java

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
}
}

Related

How to get svg in database injava

I am having 1 problem. I save SVG images in the database as binary. Now, I want to download it without converting to base64, is there any way. Thank you.
Basically, that would mean getting the BLOB object from the database.
I would follow this approach to show it in directly in the browser:
#RestController
public class ImageController {
#GetMapping(value = "/img-test", produces = "image/svg+xml")
public byte[] getImg() throws IOException
{
// retrieve your image from the DB
File imgFile = new File("C:\\Users\\USR\\Desktop\\img.svg");
InputStream inp = new DataInputStream(new FileInputStream(imgFile));
return inp.readAllBytes(); // This is a Java 9 specific convertion
}
}
With this approach, you do not change anything on the BLOB image. You take it and return it as is, an array with bytes. And you can directly show it in a browser or embed it somewhere in your HTML file.
The main thing here is the MIME type : image/svg+xml
If you are using an older version of Java, then check this question for the conversion of the InputStream object to a byte array.
And with this approach you can download the file:
#GetMapping("download-img")
public ResponseEntity downloadImg() throws IOException
{
// Get the file from the DB...
File imgFile = new File("C:\\Users\\USR\\Desktop\\img.svg");
InputStream inp = new DataInputStream(new FileInputStream(imgFile));
//Dynamically change the File Name here
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"img.svg\"")
.body(inp.readAllBytes());
}

Input image not getting read in java with getResource

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);

Loading image from a resource Can't read input file

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.

Load images in jar file

I'm trying to load an image from an executable JAR file.
I've followed the information from here, then the information from here.
This is the function to retrieve the images:
public static ImageIcon loadImage(String fileName, Object o) {
BufferedImage buff = null;
try {
buff = ImageIO.read(o.getClass().getResource(fileName));
// Also tried getResourceAsStream
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (buff == null) {
System.out.println("Image Null");
return null;
}
return new ImageIcon(buff);
}
And this is how it's being called:
logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());
With this being a simple Object.
I'm also not getting a NullPointerException unless it is being masked by the UI.
I checked the JAR file and the image is at:
/pictures/Logo1.png
This current code works both in eclipse and when it's been exported to a JAR and run in a terminal, but doesn't work when the JAR is double clicked, in which case the icon is the default JFrame icon.
Thanks for you're help. It's probably only me missing something obvious.
I had a similar problem once, which turned out to be down to issues relative addressing and my path being in the wrong place somehow. I dug this out of some old code I wrote that made it use an absolute path. That seemed to fix my problem; maybe it will work for you.
String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this);

how to get path of specific bufferedimage?

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();
}

Categories

Resources