How to write an image to file – Java ImageIO - java

I would like to write an image to a file using Java ImageIO. This is my piece of code:
Document doc = convertDocument (fileName, "grey");
ImageIO.write(Converter.convertSVGToPNG(doc), "png",
new File(FOLDER_PNG_OUT_GREY + fileName.replaceAll(".svg", ".png")));
But I get this error when running my code:
java.io.FileNotFoundException: C:\Work\eclipse-tdk\svgManager\svgManager\src\main\resources\icons\svg\grey_png\$pac.png (The system cannot find the path specified)
I also tried:
String pngFileName = FOLDER_PNG_OUT_GREY + fileName.replaceAll(".svg", ".png");
File outputfile = new File(pngFileName);
bImage = ImageIO.read(outputfile);
but then I got the error:
Can't read input file!

I suggest to get your image resource with the getResource(String file) method like this:
File initialImage = new File(YourClass.class.getResource("pac.png").getFile());

Related

How to properly reference image file in java jar?

Using java 1.8, I'm working with a Spring Boot jar file in which I'm including an image file into an Excel file using the xlsx4j package. I've got the code working to add the image file into the Excel file locally in my IDE, the problem is that it doesn't work after I compile the code into a jar file and deploy it to the server. I'm getting the following error message:
java.io.FileNotFoundException: File 'file:/opt/app/lib/myjar.jar!/BOOT-INF/classes!/myimage.jpg' does not exist
The image file exists in the src/main/resources folder in the project, and here is the code where I get the path to this file and pass it to the code that attaches the file to the Excel file:
URL imageUrl = Resources.getResource("myimage.jpg");
SpreadsheetMLPackage pkg = SpreadsheetMLPackage.createPackage();
WorksheetPart workSheetPart = pkg.createWorksheetPart(new PartName("/xl/worksheets/sheet1.xml"), "Quote", 1);
Worksheet worksheet = workSheetPart.getContents();
Drawing drawingPart = new Drawing();
Relationship drawingRel = workSheetPart.addTargetPart(drawingPart);
org.xlsx4j.sml.CTDrawing drawing = org.xlsx4j.jaxb.Context.getsmlObjectFactory().createCTDrawing();
workSheetPart.getJaxbElement().setDrawing(drawing);
drawing.setId( drawingRel.getId() );
BinaryPartAbstractImage imagePart
= BinaryPartAbstractImage.createImagePart(pkg, drawingPart,
FileUtils.readFileToByteArray(new File(imageUrl.getPath()) )); // Using path to image file here
String imageRelID = imagePart.getSourceRelationship().getId();
drawingPart.setJaxbElement(
genericExcelUtil.buildDrawingPartContentUsingCode(imageRelID));
Here is the stacktrace that I'm getting on the server:
java.io.FileNotFoundException: File 'file:/opt/app/lib/myapp.jar!/BOOT-INF/classes!/myimage.jpg' does not exist
at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:292)
at org.apache.commons.io.FileUtils.readFileToByteArray(FileUtils.java:1815)
at com.myco.myapp.util.excel.FileImpl.generateExcel(FileImpl.java:113)
at com.myco.myapp.service.impl.EmailServiceImpl.sendEmailService(EmailingServiceImpl.java:61)
at com.myco.myapp.controller.MyController.sendEmailWithDoc(MyController.java:374)
When doing a System.out.println of imageUrl.getPath(), this is what it looks like in my IDE:
/C:/Users/userid/Documents/workspace-sts-3.9.3.RELEASE/myapp/target/classes/myimage.jpg
This is what it looks like when run on the server:
file:/opt/app/lib/myapp.jar!/BOOT-INF/classes!/myimage.jpg
It seems that "new File(imageUrl.getPath())" is failing because when run from the server it cannot find the file. Any ideas on how I can handle this?
you have to load it via classpath
getClass().getResourceAsStream("/path/in/jar")
https://www.baeldung.com/reading-file-in-java
Using the suggestions provided here, I was able to open an input stream to the image file, put the contents of that input stream to a ByteArrayOutputStream, convert the ByteArrayOutputStream to a byte array, and then provide the byte array to the docx4j method:
URL imageUrl = Resources.getResource("myimage.jpg");
InputStream imageInputStream = imageUrl.openStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = imageInputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] byteArray = buffer.toByteArray();
BinaryPartAbstractImage imagePart
= BinaryPartAbstractImage.createImagePart(pkg, drawingPart, byteArray);
String imageRelID = imagePart.getSourceRelationship().getId();
drawingPart.setJaxbElement(
genericExcelUtil.buildDrawingPartContentUsingCode(imageRelID));
Thanks for the help!

Java: Read image from current src directory

I would like to load an image from my current src directory where the java class files are located as well. However, I always get an IOException..
And how can I make sure the file gets loaded properly on Mac/Linux as well on Windows?
My code so far:
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
IOException message:
Can't read input file!
(My path is correct - is it because of the space between Google and Drive?)
/Users/myMac/Google Drive/Privat/Programming/Logo_transparent.png
Kind regards and thank you!
I think It's because you didn't create the file, You can create the file if it doesn't exist by using this code
if(!imageFile.exists()) imageFile.createNewFile();
You're code will look like this
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
if(!imageFile.exists()) imageFile.createNewFile();
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
Also you shouldn't concat child files like that instead pass it as a second argument.
File imageFile = new File(System.getProperty("user.dir"), "Logo_transparent.png");
If your image files will be packaged together with your class files (for example in the same .jar) you should not use File but read it as a resource:
bufferedImage = ImageIO.read(this.getClass().getResourceAsStream("/Logo_transparent.png"));
Notice the '/' before the file name. This means to search in the root path of the classpath.
If you specify without / it will search in the package of this (the current class)
this.getClass().getResourceAsStream("Logo_transparent.png")
You can try to build the absolute path to the image like here and read it afterward.

How to convert an InputStream object to a File object?

I'm trying to get a "File" instance in a servlet called from a html form, in which I can select a PDF file on my computer.
I'm successful in getting the file as an "InputStream" but then I just cannot further convert it to a "File" object.
After a lot of different attempts, I still can't figure out what I should be doing to make it work. Any idea ?
Error :
java.io.FileNotFoundException: test.pdf (Read-only file system)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:360)
at org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:319)
at org.apache.commons.io.FileUtils.copyToFile(FileUtils.java:1552)
at org.apache.commons.io.FileUtils.copyInputStreamToFile(FileUtils.java:1528)
Code :
Part filePart = request.getPart("file");
InputStream fileContent = filePart.getInputStream();
if (fileContent != null)
{
File file = new File(filename.trim() + ".pdf");
FileUtils.copyInputStreamToFile(fileContent, file);
//use the "file" instance
//...
}
As the exception is telling you, the problem is not with "creating the file". The problem is the disk/partition is write-protected
You should create the file on a file system that is writable. Try to specify an absolute path, such as
File file = new File("/tmp/" + filename.trim() + ".pdf");
//or
file = new File("/home/userhome/" + filename.trim() + ".pdf");
The file should just be created on a writable file system.

How to get URL of Vaadin resources path?

I use Eclipse + Vaadin framework.
At first I save my image into the WEB-INF folder.
Then I load this image into the FileResource variable, create Image variable and then add Image variable into Layout.
The page URL to the image resource looks like: http://servername/sitename/APP/connector/0/16/source/qwerty1.png
How to get URL in that format for use image externally?
Variable basepath returned local path: "..../WEB-INF/qwerty1.png"
String str = (String) VaadinService.getCurrent().getBaseDirectory().
getAbsolutePath() +"/WEB-INF/qwerty1.png";
File temp = new File(str);
FileOutputStream fos = new FileOutputStream(temp);
fos.write(os.toByteArray());
fos.flush();
fos.close();
String basepath = VaadinService.getCurrent().getBaseDirectory().
getAbsolutePath() +"/WEB-INF/qwerty1.png";
FileResource resource = new FileResource(new File(basepath));
Image image2 = new Image("Image from file", resource);
addComponent(image2);
If you put the file in ...src/main/webapp/VAADIN/image.png, it should be available using for example localhost:8080/VAADIN/image.png.

Save to desktop without the exact path

I want to save a file in my desktop. So I have
FileOutputStream out = new FileOutputStream(new File("C:\\path_to_Dekstop\\print.xls"));
and it works. But I want to save the file without put the exact path to the desktop. I searched it and I found similar questions and I came up with this solution:
File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out = new FileOutputStream(new File(pathToDesktop));
but I got an error
java.io.FileNotFoundException: C:\Users\nat\Desktop (Access is denied)
pathToDesktop represents the directory of the Desktop, you should supply a file name to write to
FileOutputStream out = new FileOutputStream(new File(desktopDir, "File to be written to"));
Which will place the "File to be written to" on the desktop
You can't write directly to Desktop as its a folder but not a file. You need to write to a file. DO something like thi s:-
File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out = new FileOutputStream(new File(pathToDesktop+System.getProperty("file.separator")+"print.xls"));
This will write to print.xls in Desktop.

Categories