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);
Related
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());
}
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 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
}
}
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'm new here and kinda new to java.
I've encountered a problem.
I have a very simple program that tries to create pngs and save them in a user selected folder.
byteimage is a a private byte[]:
byteimage = bcd.createPNG(300, 140, ColorSpace.TYPE_RGB, Color.BLACK, Color.BLACK);
setPath() is called inside the action listener of the browse button
private void setPath() {
JFileChooser pathchooser = new JFileChooser();
pathchooser.setMultiSelectionEnabled(false);
pathchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
pathchooser.setApproveButtonMnemonic(KeyEvent.VK_ENTER);
pathchooser.showDialog(this, "OK");
File f = pathchooser.getSelectedFile();
if (f != null) {
filepath = f.getAbsolutePath();
pathfield.setText(filepath);
}
}
Byte to png method looks like this:
public void byteToPNG(String filename) {
try {
InputStream in = new ByteArrayInputStream(byteimage);
BufferedImage bufferedimg = ImageIO.read(in);
ImageIO.write(bufferedimg, "png", new File(filename));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
This method is called like this:
byteToPNG(pathfield.getText() + System.getProperty("file.separator") + textfield.getText() + ".png");
textfield.getText() sets the actual name of the png.
Inside the constructor, default filepath is set:
filepath = System.getProperty("user.dir");
pathfield.setText(filepath);
The code runs fine from Eclipse and it produces a png image at the desired location.
Unfortunately, after exporting as jar, it starts but when the button for generating the png is pressed, nothing happens. I'm thinking there's a problem at InputStream or BufferedImage, but I'm a bit puzzled.
If the String fileName passed to byteToPNG isn't absolute (i.e. written in the form "C:/foo/bar/etc") that could be the cause of the broken jar. You could also try running the jar file in the terminal using the command:
java -jar myJarFile.jar.
This will cause a console window to remain open alongside your running jar application in which all your applications output (including any exceptions) will be printed.