【发布时间】:2015-02-17 12:16:28
【问题描述】:
我需要从服务器下载图像并以原始质量保存,但显然保存后图像被压缩并且质量下降。
我使用 android-async-http 库来处理 http 请求。我的请求代码和保存文件:
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] response) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inPreferQualityOverSpeed=true;
Bitmap bitmap = BitmapFactory.decodeByteArray(response , 0, response .length,bmOptions);
mImageView.setImageBitmap(bitmap);
bitmapToFile(bitmap);
});
File bitmapToFile(Bitmap bitmap){
// convert Bitmap to File
File newImage;
try {
newImage = functions.createImageFile();
FileOutputStream fos = new FileOutputStream(newImage);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
Uri contentUri = Uri.fromFile(newImage);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return newImage;
}
protected File createImageFile() throws IOException {
// Create an image file name
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
【问题讨论】:
-
会不会是服务器压缩了图片?
-
“但显然图像被压缩并且质量下降” - 你是如何确定的?
-
@TimBillström 我检查了浏览器上的图像(来自 android 设备),它的大小没有改变。但是当我通过上面的代码下载它时,它的大小减少了一半。
-
好吧,作为写出图像的一部分,你自己压缩它,通过
compress()调用。 -
"质量参数不是100的意思吗?" - 不。引用
compress()的文档:“提示压缩器,0-100。0 表示压缩为小尺寸,100 表示压缩为最高质量。” “最高质量”并不意味着“不压缩”。 “如何在不压缩的情况下将位图转换为文件?” -- :: 耸耸肩:: 欢迎您直接写出byte[]。但大多数图片都是 PNG 或 JPEG,而且它们是经过压缩的。
标签: android android-async-http