Android 图片下载无法预览问题

项目去文件服务器下载图片,发现部分图片下载下来无法预览,用浏览器去下载又能成功,最后抓包发现下载图片时,http头部指定了

非压缩文件,但是服务器依然返回了 压缩文件。


   


最后解决方法,下载完成后,判断是否是压缩文件,是的话,解压缩

	public static void handleGzipFile(State state, Response response) throws Throwable {
		String mimeType = response.header("Content-Type");
		if (!TextUtils.isEmpty(mimeType)) {
			mimeType = sanitizeMimeType(mimeType);
			if (mimeType.startsWith("image/")) {
				String encoding = response.header("Content-Encoding");// 验证一下是否GZip压缩
				if (!TextUtils.isEmpty(encoding) && "gzip".equals(encoding)) {
					File ttf = new File(state.mFilename);
					File decodeFile = decodeGZipFile(ttf);
					ttf.delete();
					// 重命名之前,对临时文件,做一次图片校验,用BitmapFactory解析一下
					BitmapFactory.Options opts = new BitmapFactory.Options();
					opts.inJustDecodeBounds = true;
					BitmapFactory.decodeFile(decodeFile.getAbsolutePath(), opts);
					// 如果解析的宽高度小于1,默认为非图片
					if (opts.outWidth < 1 && opts.outHeight < 1) {
						throw new Throwable("is not a image");
					}
					if (!decodeFile.renameTo(new File(state.mFilename))) {
						throw new Throwable("rename fail!");
					}
				}
			}
		}
	}

	public static File decodeGZipFile(File file) throws IOException {
		GZIPInputStream gzipIn = null;
		FileOutputStream gzipOut = null;
		try {
			gzipIn = new GZIPInputStream(new FileInputStream(file));
			file = new File(file.getAbsolutePath() + ".gziptemp");
			gzipOut = new FileOutputStream(file);
			byte[] buf = new byte[1024 * 8];
			int num = -1;
			while ((num = gzipIn.read(buf, 0, buf.length)) != -1) {
				gzipOut.write(buf, 0, num);
			}
		} finally {
			if (gzipIn != null)
				gzipIn.close();
			if (gzipOut != null)
				gzipOut.close();
		}
		return file;
	}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值