dimanche 1 mars 2015

java does not seem to download an image correctly

after some research I figured out the easiest way for me to download an image and store it into a file.


This is my code so far:



public boolean descargarArchivo(String url, String outputDirectory) {
try {
File img = new File(outputDirectory);
URLConnection conn = new URL(url).openConnection();
conn.connect();
try (InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(img)) {
int b = 0;
while (b != -1) {
b = in.read();
if (b != -1) {
out.write(b);
}
}
}
return true;
} catch (IOException ioe) {
ioe.printStackTrace();
}
return false;
}


The issue with this code, is that it sometimes performs a wrong download of the picture. Let me clear the idea with an example:


Original Image enter image description here


While the first picture is the original image (and the output file should be like that), the second picture is the real output file of the image, performed by that code, which is, clearly wrong (ignore the resolution, I'm just talking about this "wrong pixels"). Is there any way to improve this? Should I change the way to download images from the web?


Aucun commentaire:

Enregistrer un commentaire