0

Пытаюсь сохранить картинку, ничего не выходит. Использую два метода для сохранения и загрузки

 private String saveToInternalStorage(Bitmap bitmapImage) throws IOException {
    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,"user.png");

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

private void loadImageFromStorage(String path)
{
    try {
        Toast.makeText(this, "Загружено", Toast.LENGTH_LONG).show();
        File f=new File(path, "user.png");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
        channelLogo.setImageBitmap(b);
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

Здесь сохраняю картинку посредством нажатия на кнопку меню

case R.id.save:
            Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                    R.drawable.user);
            try {
                saveToInternalStorage(icon);
                Toast.makeText(this, "Сохранено", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return true;

Здесь загружаю. Метод расположил в методе OnCreate

loadImageFromStorage("/data/data/yourapp/app_data/imageDir");
4
  • 2
    А ошибка в ... ?
    – iFr0z
    2 авг 2016 в 12:14
  • @YuraIvanov боюсь, без Вас мы не справимся.
    – iFr0z
    2 авг 2016 в 12:22
  • /data/data/yourapp/app_data/imageDir - это как пример. Вместо your_app - название пакета программы
    – Ziens
    2 авг 2016 в 12:30
  • в loadImageFromStorage нужно подставлять то, что вернул метод saveToInternalStorage
    – Ziens
    2 авг 2016 в 12:38

2 ответа 2

1

Попробуйте этот код, у меня работает!

 /**Method for save bitmap object
 * to file directory on device
 *
 * @param fileName file name need concat format: fileName + ".png"
 * @param bitmap
 * @return true if object be saved
 */
public boolean saveImageToFile(String fileName, Bitmap bitmap) {

    File imageFile =
            new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator
                    + "folderName"
                    ,fileName);

    Bitmap.CompressFormat format = Bitmap.CompressFormat.PNG;
    int quality = 100;

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(imageFile);

        bitmap.compress(format, quality, fileOutputStream);

        fileOutputStream.close();

        return true;
    }
    catch (IOException e) {
        Log.e("app",e.getMessage());
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    return false;
}

/**Method for get user bitmap
 * from file directory on device
 *
 * @param fileName file name need  format: "fileName" + ".png"
 * @return drawable
 */
public Drawable getImageFromFile(String fileName) {
    Drawable drawable;
    String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator
                    + "folderName"
                    + File.separator
                    + fileName;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap photo = BitmapFactory.decodeFile(path, options);

    drawable = new BitmapDrawable(photo);
    return drawable;
}
1
private void saveToInternalStorage(Bitmap bitmapImage) throws IOException {
    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, "user.png");
    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();
    }
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.edit().putString("image_path", directory.getAbsolutePath()).commit();
}

private void loadImageFromStorage() {
    try {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String path = prefs.getString("image_path", "");
        Toast.makeText(this, "Загружено", Toast.LENGTH_LONG).show();
        File f = new File(path, "user.png");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
        channelLogo.setImageBitmap(b);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Все работает

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.