Saving and Reading Bitmaps/Images from Internal memory in Android

前端 未结 7 1504
傲寒
傲寒 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: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();
        }
    
    }
    

提交回复
热议问题