如何将位图转换为文件而不进行压缩

4
我需要从服务器下载图片并以其原始质量保存,但是保存后,图片被压缩且质量下降。我使用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;
}

@CommonsWare 我检查了大小,在服务器上是300千字节,在设备上保存后变成了150。这可能是解码问题吗?我如何在解码之前检查byte[]内容以确保它的正确性? - Ann
@CommonsWare 我更新了我的帖子。 - Ann
2
好的,通过compress()调用,您自己压缩图像作为写出图像的一部分。 - CommonsWare
@CommonsWare,质量参数100不是表示不压缩吗?如何将位图转换为文件而不压缩它? - Ann
1
“quality参数100不是不压缩吗?” - 不是。引用compress()的文档:“压缩提示,范围0-100。0表示为小尺寸而压缩,100表示为最高质量而压缩。” “最高质量”不意味着“不压缩”。 “如何将位图转换为File而不进行压缩?” - ::耸肩:: 您可以直接写出byte[]。但大多数图像都是PNG或JPEG格式,并且它们已经经过压缩。 - CommonsWare
显示剩余6条评论
1个回答

0
摆脱那个BitmapFactory,在参数byte[] response中直接保存所有字节到文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接