如何在不压缩的情况下将位图转换为文件

时间:2015-02-17 12:16:28

标签: android android-async-http

我需要从服务器下载图像并将其保存为原始质量,但显然保存后的图像会被压缩并且质量下降。

我使用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;
}

1 个答案:

答案 0 :(得分:0)

取消该BitmapFactory,只将参数byte[] response中的所有字节直接保存到文件中。