How to convert bitmap to File without compressing

2019-06-03 06:37发布

I need to download image from a server and save it in its original quality, but apparently the after saving the image is compressed and the quality decreased.

I use android-async-http library for http requests. my code of the request and saving file:

     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条回答
乱世女痞
2楼-- · 2019-06-03 07:27

Do away with that BitmapFactory and just save all the bytes in parameter byte[] response directly to file.

查看更多
登录 后发表回答