kgautron
kgautron

Reputation: 8263

Java image copy ok on windows but altered on linux

I download a picture from a URL with the following method :

private void download(String srcUrl, String destination) throws Throwable {
    File file = new File(destination);
    if (!file.exists()) {
        file.createNewFile();
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        BufferedInputStream in = new BufferedInputStream(new URL(srcUrl).openStream());
        byte bytes[] = new byte[1024];
        while (0 <= in.read(bytes, 0, 1024)) {
            out.write(bytes);
        }
        out.close();
        in.close();
    }
}

On windows the resulting picture is a perfect copy of the original. However on my debian server, the picture is altered: the bottom right area of the picture is blur. It happens on every picture, and it is always on the same area of the picture.

Thanks a lot for any help!

Upvotes: 4

Views: 250

Answers (1)

user166390
user166390

Reputation:

I don't know why the result are different between systems, although the code is flawed and I suspect it has something to do with the observed behavior.

while (0 <= in.read(bytes, 0, 1024)) {
    out.write(bytes);
}

Should be:

int count;
while ((count = in.read(bytes, 0, 1024)) > 0) {
    out.write(bytes, 0, count);
}

Otherwise there is a [high] chance "garbage" is written at the end which might explain the blurriness, depending on the program that tries to view the [corrupted] image file. (The size of the array used as the buffer does not change -- should only write out as much data as was written to it.)

Happy coding.

Upvotes: 5

Related Questions