How to save pictures in SharedPreferences ?

    1 answer 1

    Use the code below to save the image in the internal directory:

     private String saveToInternalStorage(Bitmap bitmapImage){ ContextWrapper cw = new ContextWrapper(getApplicationContext()); // путь /data/data/yourapp/app_data/imageDir File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); // Создаем imageDir File mypath=new File(directory,"profile.jpg"); FileOutputStream fos = null; try { fos = new FileOutputStream(mypath); // Используем метод сжатия BitMap объекта для записи в OutputStream bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); } catch (Exception e) { e.printStackTrace(); } finally { fos.close(); } return directory.getAbsolutePath(); } 

    To read the file from the internal memory. Use the code below.

     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(); } } 

    A source


    Thus, the picture is also saved in the closed folders of your application in the system, and already in SharedPreferences you can save the path to this picture, i.e. what saveToInternalStorage returns.

    SharedPreferences intended for storing simple variables of type String , int ... It is much more logical and, as I think it is more correct, to store there only the path to the picture, and the picture itself in its original form next to the same settings. "A simple and easy mechanism based on key-value pairs and designed to store primitive application data, most often user settings."

    • What do not you like? SharedPreferences is intended for storing simple variables of the String type, int ... Gonrazdo is more logical and, as I consider it more correct, to store there only the path to the picture, and the picture itself in its original form next to the same settings. - Ziens
    • "A simple and easy mechanism based on key-value pairs and designed to save the primitive data of the application, most often user settings" - suvitruf.ru/2012/09/17/1916 - Ziens
    • 2
      I think that I don’t like the fact that you just copied a part of the answer without even bothering to translate. And the resource is called "Stack Overflow in Russian", and not "copy-paste with Stack Overflow" - pavlofff
    • @pavlofff Corrected - iFr0z
    • @YuraIvanov I hope everyone is happy with everything. - iFr0z