Save bitmap to location

前端 未结 19 2425
悲哀的现实
悲哀的现实 2020-11-22 00:20

I am working on a function to download an image from a web server, display it on the screen, and if the user wishes to keep the image, save it on the SD card in a certain fo

19条回答
  •  囚心锁ツ
    2020-11-22 00:45

    You should use the Bitmap.compress() method to save a Bitmap as a file. It will compress (if the format used allows it) your picture and push it into an OutputStream.

    Here is an example of a Bitmap instance obtained through getImageBitmap(myurl) that can be compressed as a JPEG with a compression rate of 85% :

    // Assume block needs to be inside a Try/Catch block.
    String path = Environment.getExternalStorageDirectory().toString();
    OutputStream fOut = null;
    Integer counter = 0;
    File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten.
    fOut = new FileOutputStream(file);
    
    Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
    pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
    fOut.flush(); // Not really required
    fOut.close(); // do not forget to close the stream
    
    MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
    

提交回复
热议问题