Java图像复制ok在Windows上,但在Linux上更改

kga*_*ron 4 java image file download

我使用以下方法从URL下载图片:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在Windows上,生成的图片是原始图片的完美副本.但是在我的debian服务器上,图片被改变了:图片的右下方区域是模糊的.它发生在每张图片上,并且始终位于图片的同一区域.

非常感谢您的帮助!

小智 5

我不知道为什么系统之间的结果不同,虽然代码存在缺陷,我怀疑它与观察到的行为有关.

while (0 <= in.read(bytes, 0, 1024)) {
    out.write(bytes);
}
Run Code Online (Sandbox Code Playgroud)

应该:

int count;
while ((count = in.read(bytes, 0, 1024)) > 0) {
    out.write(bytes, 0, count);
}
Run Code Online (Sandbox Code Playgroud)

否则有一个[高]机会"垃圾"写在最后,这可能解释模糊,这取决于试图查看[损坏]图像文件的程序.(用作缓冲区的数组的大小不会改变 - 只应写出与写入数据一样多的数据.)

快乐的编码.