Saving and Reading Bitmaps/Images from Internal memory in Android

前端 未结 7 1364
傲寒
傲寒 2020-11-22 02:59

What I want to do, is to save an image to the internal memory of the phone (Not The SD Card).

How can I do it?

I have got the image directly

相关标签:
7条回答
  • 2020-11-22 03:10
    /**
     * Created by Ilya Gazman on 3/6/2016.
     */
    public class ImageSaver {
    
        private String directoryName = "images";
        private String fileName = "image.png";
        private Context context;
        private boolean external;
    
        public ImageSaver(Context context) {
            this.context = context;
        }
    
        public ImageSaver setFileName(String fileName) {
            this.fileName = fileName;
            return this;
        }
    
        public ImageSaver setExternal(boolean external) {
            this.external = external;
            return this;
        }
    
        public ImageSaver setDirectoryName(String directoryName) {
            this.directoryName = directoryName;
            return this;
        }
    
        public void save(Bitmap bitmapImage) {
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(createFile());
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        @NonNull
        private File createFile() {
            File directory;
            if(external){
                directory = getAlbumStorageDir(directoryName);
            }
            else {
                directory = context.getDir(directoryName, Context.MODE_PRIVATE);
            }
            if(!directory.exists() && !directory.mkdirs()){
                Log.e("ImageSaver","Error creating directory " + directory);
            }
    
            return new File(directory, fileName);
        }
    
        private File getAlbumStorageDir(String albumName) {
            return new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES), albumName);
        }
    
        public static boolean isExternalStorageWritable() {
            String state = Environment.getExternalStorageState();
            return Environment.MEDIA_MOUNTED.equals(state);
        }
    
        public static boolean isExternalStorageReadable() {
            String state = Environment.getExternalStorageState();
            return Environment.MEDIA_MOUNTED.equals(state) ||
                    Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
        }
    
        public Bitmap load() {
            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(createFile());
                return BitmapFactory.decodeStream(inputStream);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }
    

    Usage

    • To save:

      new ImageSaver(context).
              setFileName("myImage.png").
              setDirectoryName("images").
              save(bitmap);
      
    • To load:

      Bitmap bitmap = new ImageSaver(context).
              setFileName("myImage.png").
              setDirectoryName("images").
              load();
      

    Edit:

    Added ImageSaver.setExternal(boolean) to support saving to external storage based on googles example.

    0 讨论(0)
  • 2020-11-22 03:13

    Use the below code to save the image to internal directory.

    private String saveToInternalStorage(Bitmap bitmapImage){
            ContextWrapper cw = new ContextWrapper(getApplicationContext());
             // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            // Create imageDir
            File mypath=new File(directory,"profile.jpg");
    
            FileOutputStream fos = null;
            try {           
                fos = new FileOutputStream(mypath);
           // Use the compress method on the BitMap object to write image to the OutputStream
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
            } catch (Exception e) {
                  e.printStackTrace();
            } finally {
                try {
                  fos.close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
            } 
            return directory.getAbsolutePath();
        }
    

    Explanation :

    1.The Directory will be created with the given name. Javadocs is for to tell where exactly it will create the directory.

    2.You will have to give the image name by which you want to save it.

    To Read the file from internal memory. Use below code

    private void loadImageFromStorage(String path)
    {
    
        try {
            File f=new File(path, "profile.jpg");
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
                ImageView img=(ImageView)findViewById(R.id.imgPicker);
            img.setImageBitmap(b);
        } 
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 03:15

    if you want to follow Android 10 practices to write in storage, check here and if you only want the images to be app specific, here for example if you want to store an image just to be used by your app:

    viewModelScope.launch(Dispatchers.IO) {
                getApplication<Application>().openFileOutput(filename, Context.MODE_PRIVATE).use {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 50, it)
                }
            }
    

    getApplication is a method to give you context for ViewModel and it's part of AndroidViewModel later if you want to read it:

    viewModelScope.launch(Dispatchers.IO) {
                val savedBitmap = BitmapFactory.decodeStream(
                    getApplication<App>().openFileInput(filename).readBytes().inputStream()
                )
            }
    
    0 讨论(0)
  • 2020-11-22 03:20

    // mutiple image retrieve

     File folPath = new File(getIntent().getStringExtra("folder_path"));
     File[] imagep = folPath.listFiles();
    
     for (int i = 0; i < imagep.length ; i++) {
         imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
     }
     imagesAdapter.notifyDataSetChanged();
    
    0 讨论(0)
  • 2020-11-22 03:22
        public static String saveImage(String folderName, String imageName, RelativeLayout layoutCollage) {
            String selectedOutputPath = "";
            if (isSDCARDMounted()) {
                File mediaStorageDir = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
                // Create a storage directory if it does not exist
                if (!mediaStorageDir.exists()) {
                    if (!mediaStorageDir.mkdirs()) {
                        Log.d("PhotoEditorSDK", "Failed to create directory");
                    }
                }
                // Create a media file name
                selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
                Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
                File file = new File(selectedOutputPath);
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    if (layoutCollage != null) {
                        layoutCollage.setDrawingCacheEnabled(true);
                        layoutCollage.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
                    }
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return selectedOutputPath;
        }
    
    
    
    private static boolean isSDCARDMounted() {
            String status = Environment.getExternalStorageState();
            return status.equals(Environment.MEDIA_MOUNTED);
        }
    
    0 讨论(0)
  • 2020-11-22 03:25

    For Kotlin users, I created a ImageStorageManager class which will handle save, get and delete actions for images easily:

    class ImageStorageManager {
        companion object {
            fun saveToInternalStorage(context: Context, bitmapImage: Bitmap, imageFileName: String): String {
                context.openFileOutput(imageFileName, Context.MODE_PRIVATE).use { fos ->
                    bitmapImage.compress(Bitmap.CompressFormat.PNG, 25, fos)
                }
                return context.filesDir.absolutePath
            }
    
            fun getImageFromInternalStorage(context: Context, imageFileName: String): Bitmap? {
                val directory = context.filesDir
                val file = File(directory, imageFileName)
                return BitmapFactory.decodeStream(FileInputStream(file))
            }
    
            fun deleteImageFromInternalStorage(context: Context, imageFileName: String): Boolean {
                val dir = context.filesDir
                val file = File(dir, imageFileName)
                return file.delete()
            }
        }
    }
    

    Read more here

    0 讨论(0)
提交回复
热议问题