New line character is appended when a image is downloaded from url - java

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.

Related

ImageIO Unexpected end of ZLIB input stream

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.

How to convert InputStream to a PDF in Java, without damaging the file?

I have an InputStream which I would like to convert to a PDF, and save that PDF in a directory. Currently, my code is able to convert the InputStream to a PDF and the PDF does show up in the correct directory. However, when I try to open it, the file is damaged.
Here is the current code:
InputStream pAdESStream = signingServiceConnector.getDirectClient().getPAdES(this.statusReader.getStatusResponse().getpAdESUrl());
byte[] buffer = new byte[pAdESStream.available()];
pAdESStream.read(buffer);
File targetFile = new File(System.getProperty("user.dir") + "targetFile2.pdf");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
Originally, the InputStream was a pAdES-file (https://en.wikipedia.org/wiki/PAdES). However, it should be able to be read as just a regular PDF.
Does anyone know how to convert the InputStream to a PDF, without getting a damaged PDF as a result?
Hello it might be a bit late but you can use PDFBOX api (or itextpdf)
https://www.tutorialkart.com/pdfbox/create-write-text-pdf-file-using-pdfbox/
here is a tuto of the process gl

How to download monthly Treasury Files

Up till early this year the US Treasury web site posted monthly US Receipts and Outlays data in txt format. It was easy to write a program to read and store the info. All I use were:
URL url = new URL("https://www.fiscal.treasury.gov/fsreports/rpt/mthTreasStmt/mts1214.txt")
URLConnection connection.openConnection();
InputStream is = connection.getInputStream();
Then I just read the InputStream into a local file.
Now when I try same code, for May, I get an InputStream with nothing in it.
Just clicking on "https://www.fiscal.treasury.gov/fsreports/rpt/mthTreasStmt/mts0415.xlsx" opens an excel worksheet (the download path has since changed).
Which is great if you don't mind clicking on each link separately ... saving the file somewhere ... opening it manually to enable editing ... then saving it again as a real .xlsx file (because they really hand you an .xls file.)
But when I create a URL from that link, and use it to get an InputStream, the is empty. I also tried url.openStream() directly. No different.
Can anyone see a way I can resume using a program to read the new format?
In case its of interest I now use this code to write the stream to the file bit by bit... but there are no bits, so I don't know if it works.
static void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
System.out.println("reading: " + in.read(buf));
//This is what tells me it is empty, i.e. the loop below is ignored.
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Any help is appreciated.

Read image file from same package [duplicate]

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

Not able to delete image file after image conversion from PNG to TIF

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.

Categories