问题描述
在测试功能的时候发现远程图片下载到本地的时候图片严重失真,在往上找的解决方案也都不适用,比如用BufferedOutputStream字节数组输出等等。
在后来的排查过程中发现,在下图位置打debug进行断点拍查,输出的文件就完全没有任何问题
解决方法
在进行输出的时候,多加两个参数。
完整代码
String uploadPath = sysSetting.getUploadPath();
String path = uploadPath + File.separator + "wxheadimg" +File.separator +memberCode+".jpg";
//目标存放地址
File filePath =new File(path);
//校验文件夹目录是否存在,不存在就创建一个目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
String wxHeadUrl = fxMember.getWxHeadUrl();
URL headUrl = new URL(wxHeadUrl);
InputStream is = headUrl.openStream();//远程图片使用URL来进行读取
OutputStream os = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
int length = 0;
while (-1 != (length = is.read(buffer,0,buffer.length))){
os.write(buffer,0,length);
}
os.close();
is.close();