Как создать файл ".nomedia" и сохранить в нем изображения программным способом? - PullRequest
0 голосов
/ 21 декабря 2018

Для моего приложения изображения хранятся во внутреннем хранилище моего телефона, и изображения видны в галерее, но мой клиент хочет, чтобы изображения не были видны внутри галереи.

Я вручную добавил файл .nomedia в папку, где хранятся изображения, и он исчезает, но я снова взял новое изображение, которое видно в галерее.

Так как я могу сделать это программно, чтобы изображения не появлялись в моей галерее?

Вот мой код.

public  void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode,data);

if(resultCode== Activity.RESULT_OK){

    if(requestCode==REQUEST_CAMERA){
        Uri selectedImageUri = data.getData();
        if (null != selectedImageUri) {
            // Get the path from the Uri

            String path = getPathFromURI(selectedImageUri);
            File file = new File(path);
            Bitmap  bmp = CommonMethod.compressImage(file, getContext());
            Log.e(TAG, "onActivityResult --: "+ String.format("Size : %s", getReadableFileSize(file.length())));

            mCustomerImage =  CommonMethod.bitmapToByteArray(bmp);
            imageTemplateStr = Base64.encodeToString(mCustomerImage, Base64.DEFAULT);
            Log.e(TAG, "image: "+ imageTemplateStr );
            imageCustomer.setImageBitmap(bmp);
        }

    }else if(requestCode==SELECT_FILE){
        Uri selectedImageUri = data.getData();
        if (null != selectedImageUri) {
            // Get the path from the Uri

            String path = getPathFromURI(selectedImageUri);
            File file = new File(path);
            Bitmap  bmp = CommonMethod.compressImage(file, getContext());
            Log.e(TAG, "onActivityResult --: "+ String.format("Size : %s", getReadableFileSize(file.length())));

            mCustomerImage =  CommonMethod.bitmapToByteArray(bmp);
            imageTemplateStr = Base64.encodeToString(mCustomerImage, Base64.DEFAULT);
            Log.e(TAG, "image: "+ imageTemplateStr );

            imageCustomer.setImageBitmap(bmp);
        }

}

метод getPathFromUri

public String getPathFromURI(Uri contentUri) {
    String res = null;
    String[] proj = {MediaStore.Images.Media.DATA};
    Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
    if (cursor.moveToFirst()) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        res = cursor.getString(column_index);
    }
    cursor.close();
    return res;
}

метод compressImage ().

public static Bitmap compressImage(File imgFile, Context context) {
    Bitmap compressedImgBitmap = new Compressor.Builder(context)
            .setMaxWidth(640)
            .setMaxHeight(480)
            .setCompressFormat(Bitmap.CompressFormat.PNG)
            .build()
            .compressToBitmap(imgFile);


    return compressedImgBitmap;
}

Ответы [ 2 ]

0 голосов
/ 25 марта 2019

Создание файла .nomedia в хранилище для скрытия аудио из медиаплеера:

String filepath = Environment.getExternalStorageDirectory().getPath()+"/";

File file = new File(filepath+".nomedia");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
0 голосов
/ 21 декабря 2018
File files = getExternalFilesDir("");
File root = new File(files.getAbsolutePath()+"/Saveimags");
  if (!root.exists()) {
     root.mkdirs();
  }
File gpxfile = new File(root, ".nomedia");
FileWriter writer = new FileWriter(gpxfile);
writer.flush();
writer.close();


       File path = new File(root, "dump.png");
            try {
                FileOutputStream out = new FileOutputStream(path);
                Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
                myBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

Android / данные / имя вашего пакета / файлы / это путь к папке с данными Android после того, как вы сможете сохранить изображение в этой папке.

...