I have the following code for looping through file in a directory and resizing them to 64x64 pixels.
for(File file: friedFiles){
System.out.println(file.getPath());
BufferedImage image = ImageIO.read(file);
Image resize = image.getScaledInstance(64,64, Image.SCALE_DEFAULT);
File resizedFile = new File(path + "\\" + file.getName());
ImageIO.write(convertToBufferedImage(resize), "png", resizedFile);
}
System.out.println("Files finished");
This works fine but after around the 300th image in this directory it breaks, the error it gives is "Caused by: java.io.EOFException: Unexpected end of ZLIB input stream" on the line
BufferedImage image = ImageIO.read(file);
I am unsure what is causing this as the file it is trying to read is a valid image file.
EDIT: Please see the answer I added to this question the issue was a corrupted file header in the original file.
The problem turned out to be a corrupted file header, I was able to fix this problem by regenerating the original file and adding a try catch block to catch an EOFException so that in any future files it can output an error on that specific file and carry on to parse the rest of directory of files.
Related
I'm using Java 11, attempting to write compressed TIFF images with ImageIO. Most images write correctly, but some images throw an IIOException from within the javax.imageio code. My application is using Graphics 2D to resize images, then writing them to file. The Exception is:
javax.imageio.IIOException: I/O error writing TIFF file!
Here is the code snippet where I create the ImageWriter and write the image. The Exception is thrown from the last line in this snippet, tiffWriter.write().
//Create the TiffWriter, tell it where to write
ImageWriter tiffWriter = ImageIO.getImageWritersByFormatName("tiff").next();
tiffWriter.setOutput(imageOut);
//Wrap up the BufferedImage and Metadata in the IIOImage
IIOImage iioImg = new IIOImage(bi, null, meta);
//Set some writing parameters, so we get the G4 compression
ImageWriteParam writeParam = tiffWriter.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionType(COMPRESSION_TYPE_GROUP4FAX);
//Write the image
tiffWriter.write(null, iioImg, writeParam);
The relevant stack trace entries are:
File=TIFFImageWriter.java,Class=com.sun.imageio.plugins.tiff.TIFFImageWriter,Method=write,Line=2612
File=TIFFImageWriter.java,Class=com.sun.imageio.plugins.tiff.TIFFImageWriter,Method=write,Line=2315
There is no further information given. So I'm not really sure what steps to take next. I know that I have write permission in the destination location. I can't seem to find any pattern with the images that fail the write operation. It seems like a roughly 20% failure rate in my sample.
Has anyone else experienced this error when writing TIFF files?
EDIT:
Just to clarify, I am setting the compression type to "CCITT T.6". The compression definitely has something to do with this error. If I omit the lines:
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionType(COMPRESSION_TYPE_GROUP4FAX);
Then the IIOException is not thrown!
In my batch of test images, the same images fail no matter what the compression type is. But if there is no compression, all images are written successfully.
So I guess the question is, why does writing a compressed image fail here?
We are trying to download an image file from url https://test.com/images/123.jpg
URL url = new URL("https://test.com/images/123.jpg");
InputStream inputStream = url.openStream();
byte[] buffer = new byte[2048];
pResponse.setContentType("application/octet-stream");
pResponse.setHeader("Content-Disposition","attachment;filename=\""123.jpg\"");
while ((inputStream.read(buffer)) != -1) {
pResponse.getOutputStream().write(buffer);
}
pResponse.getOutputStream().flush();
pResponse.getOutputStream().close();
inputStream.close();
The downloaded file is corrupted. Click here for screenshot. When I tried to open the file with Notepad++, a empty line is appended at the beginning of the file.
On saving the file by removing the empty line at the beginning of the file, We are able to open the image successfully.
When I changed the code and not writing the bytes to pResponse.getOutputStream() then the image downloaded has an empty line.
So, How can we remove that empty line or reset the output stream to empty
Please correct me if I am wrong
Regards,
John
I do not know why empty line is getting appended, but when tries to create the same scenario of downloading a file i used this code and it is working fine:
URL url = new URL("http://localhost:8080/HTMLCS/Images/OCR.PNG");
BufferedImage img = ImageIO.read(url);
File file = new File("C:\\Users\\username\\Desktop\\RegressionTests\\OCR.png");
ImageIO.write(img, "png", file);
It may or may not be helpful to you but you should give it a try.
Please do let me know if i was not able to understand your question correctly.
i am copying a file like this:
File copy = new File(file.getName());
// path relative to current working directory
Path relativePath = Paths.get("src/main/resources/images/", copy.getPath());
java.nio.file.Files.copy(
file.toPath(), // input path
relativePath, // target path
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
logger.info("Copy file to path {}", relativePath);
// save path for NPC
currentImagePath = "/images/"+copy.getPath();
and then save the path to the database. When I try to open the copied file like this:
Image image = new Image(bild);
(bild is the currentImagePath from before), I get an Exception saying that it was an invalid URL or the resource was not found. However, if I end the program and start it anew, opening the file works without a problem. Is there a solution to this?
Maybe the file is not done copying yet. It could take the OS a while to copy the file. The copy method might return before the copy is complete.
Without seeing more code I would say that your issue is this line Image image = new Image(bild);.
Also "/images/"+copy.getPath() is not the same as relativePath, are you using them both correctly? Try this to check if there is an issue:
System.out.println("/images/"+copy.getPath());
System.out.println(relativePath);
System.out.println(copy.getAbsolutePath());
Was your issue caused by an incorrect path?
Now try something a bit like this to load your image (Note how ImageIO is used):
System.out.println("Does file exist: "+ copy.exists());
System.out.println("Is file locked: "+ copy.canWrite());
while (copy.canWrite() != true){
//stall your application until the file is accessible.
}
//now load the file
Image image = ImageIO.read(copy);
This answer has excellent info on checking for a locked file:
https://stackoverflow.com/a/1500521/1270000
This question already has answers here:
Including Images with an executable jar
(2 answers)
Closed 9 years ago.
I want to read a bunch of image files from my current package because I want to get access to the files when my package which includes my image files is exported to others' computer.
I just want to make sure my program can read the images no matter if the package is in my computer.
I tried
File file = new File("images.jpg"); // It is wrong because the path is wrong.
// I want to assign the image as BuffuredImage
BufferedImage dealerCardImage1 = ImageIO.read(file);
I was wondering how the path of the files should be. What should I do?
put your image file inside the package of current class file and try this:
BufferedImage dealerCardImage1 = ImageIO.read(getClass().getResourceAsStream("images.jpg"));
Note that, getClass().getResourceAsStream(path) returns an InputStream that points to a path that starts from current package.
For example if you have a class file named HelloWorld inside package com.example, then HelloWorld.class.getResourceAsStream("images.jpg") returns an InputStream to image with this path: com/example/images.jpg
if you read from file use
Image image = new Image();
image = ImageIO.read(file);
// Read from an input stream
InputStream is = getClass()
.getResourceAsStream("/com/statement/SamplePDFStatementFile.txt");
image = ImageIO.read(is);
//if you read from url
// Read from a URL
URL url = new URL("http://hostname.com/image.gif");
image = ImageIO.read(url);
ImageIO.read(file); will return null if no registered ImageReader is not found.
Please check whether you have registered any ImageReader or not.
I think this code snippet could help you
File file = new File("images.jpg"); // Assuming images.jpg in my working directory
FileInputStream fis = new FileInputStream(file);
BufferedImage image = ImageIO.read(fis); //reading the image file
You just need to wrap the file into an FileInputStream and then pass it to read()
I am creating .PNG file using BufferedImage with some test. Now after creating image I am trying to convert .PNG image to .TIF, which is working fine. Now once I create TIF image, I want to delete PNG image. But because of some reason, I am not able to do this. There is no any exception for this.
Here is my code
File pngFile = null;
FileOutputStream fOut = null;
try {
pngFile = new File("C:\\Test.PNG");
fOut = new FileOutputStream ("C:\\Test.TIF");
RenderedOp src = JAI.create("fileload", "C:\\Test.PNG");
TIFFImageEncoder encoder = new TIFFImageEncoder (fOut, null);
encoder.encode (src);
}catch(Exception e) {
}finally {
fOut.close();
System.out.println(pngFile.delete());
}
Well there's definitely no exception since your catch block is empty.
Something may be still holding a handle to the file, not allowing it to be deleted.
I would examine JAI.create, RenderedOp and the TiffEncoder.
Instead of providing the file path as string you can provide input stream and in finally first close the input stream and then delete the file. This may work.
I was facing same problem sometime before. The best way to do it in this is to first dispose the resources using the image object you have create, like below-
var image = Image.FromFile(pngTarget); // here pngTarget is my PNG file's name along with complete path.
// your code to convert png to tiff
.
.
.
at the end of the method you can write below -
image.Dispose(); // the image object I have created above
File.Delete(pngTarget); // delete the file
Also, don't forget to flush/close the memory stream, if using any.
Thanks.