
png和jpg作为两种最常用的图片格式,首先我们要知道他们的区别:
1.从一般图片的外观上来说,他们是无法直接判断的
2.从文件大小上来说,同样一张图png肯定比jpg的大
3.通过查资料咱们可以发现,png即可移植网络图形格式,也是一种位图文件存储格式,可以进行无损压缩。而jpg是我们最常见的图片格式了,图片占用存储较少,但是也牺牲了图片质量。
总结为一句话是两者最大的区别是有损和无损。
而出现加载透明png图片变黑的问题,一般情况下这样的:
服务端的图片是透明png的无损图片,我们下载到本地的时候强制把它处理为了jpg的形式,造成图片质量有损。
jpg图片是没有背景透明这个概念的。
图片下载保存到本地SD卡的工具方法,可以使用如下代码:
/**
* 将文件写到本地缓存
* @param fileName
* @param in
* @param length 总的文件长度
* @param callBack 下载回调接口
*/
private static void writeToLocal(String fileName, InputStream in,int length,DownloadCallback callback) {
if(in == null) {
return;
}
FileOutputStream out = null;
byte[] buffer = new byte[1024];
int len = -1;
long count = 0;
try {
out = new FileOutputStream(fileName);// 为图片文件实例化输出流
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
count += len; if(callback != null) {
callback.onDownload(length, count, false, false);
}
} if(callback != null) {
callback.onDownload(length, count, true, false);
} out.flush();
out.close();
in.close();
} catch (IOException e1) {
e1.printStackTrace();
try {
if (out != null) {
out.close();
out = null;
} in.close();
in = null;
} catch (IOException e) {
e.printStackTrace();
} // 网络出现异常,删除下载文件
new File(fileName).delete();
if(callback != null) {
callback.onDownload(length, count, false, true);
}
}
}