我使用以下方法从 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();
}
}
在 Windows 上生成的图片是原始图片的完美副本。但是在我的 debian 服务器上,图片发生了变化:图片右下角的区域模糊不清。它发生在每张图片上,并且总是在图片的同一区域。
非常感谢您的帮助!
最佳答案
我不知道为什么系统之间的结果不同,尽管代码有缺陷并且我怀疑它与观察到的行为有关。
while (0 <= in.read(bytes, 0, 1024)) {
out.write(bytes);
}
应该是:
int count;
while ((count = in.read(bytes, 0, 1024)) > 0) {
out.write(bytes, 0, count);
}
否则,很可能在末尾写入“垃圾”,可能解释模糊,这取决于试图查看[损坏的]图像文件的程序。 (用作缓冲区的数组的大小不会改变——应该只写出与写入其中一样多的数据。)
快乐编码。
关于Java 图像复制在 Windows 上正常,但在 Linux 上已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781441/