将图像从imageview保存到特定的库文件夹API 23

时间:2017-01-02 09:48:07

标签: java android permissions imageview downloading

嗯,基本上我需要我的代码才能在库中创建一个名为" MotiMate"并将从特定imageview检索到的图像保存到该文件夹​​中。此外,我需要处理存储权限授予方法,因为我的目标是API 23.任何方法都可以吗?

代码:

public void downloadImageToGallery() {
    File filepath = Environment.getExternalStorageDirectory();
    File dir = new File(filepath.getAbsolutePath() + "/MotiMate/");
    dir.mkdirs();

    ImageView iv = (ImageView) findViewById(R.id.imageView);
    iv.setDrawingCacheEnabled(true);
    bitmap = iv.getDrawingCache();
    String title = quoteType+n+".jpg";
    file = new File(dir, title);
    if(file.exists()) {
        file.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
        isStoragePermissionGranted();
    } catch (Exception e) {
        e.printStackTrace();
    }

    Toast.makeText(this, "Downloading...", Toast.LENGTH_SHORT).show();
}
public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("", "Permission is granted");
            addImageToGallery(file.getAbsolutePath(), Quote.this);
            return true;
        } else {

            Log.v("","Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v("","Permission is granted");
        addImageToGallery(file.getAbsolutePath(), Quote.this);
        return true;
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED) {
        Log.v("","Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}
public static void addImageToGallery(final String filePath, final Context context) {
    ContentValues values = new ContentValues();

    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.MediaColumns.DATA, filePath);

    context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}

2 个答案:

答案 0 :(得分:1)

File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + "/MESSAGES/");
    if (!wallpaperDirectory.exists()) {
        if (!wallpaperDirectory.mkdirs()) {
            // have the object build the directory structure, if needed.
            wallpaperDirectory.mkdirs();
        }
    }
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(wallpaperDirectory, fname);
    if (file.exists()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

        MediaScannerConnection.scanFile(context, new String[]{file.toString()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                    }
                }
        );

    } catch (Exception e) {
        e.printStackTrace(); 
    }

使用此代码对我有用..并且还允许

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
<\ n>在您的清单文件中。

您活动中的手动提交

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE) !=
            PackageManager.PERMISSION_GRANTED) {
        final String[] permission = new String[]{
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.INTERNET,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.GET_ACCOUNTS,
                android.Manifest.permission.WAKE_LOCK,
                android.Manifest.permission.RECEIVE_SMS,
                android.Manifest.permission.PACKAGE_USAGE_STATS,
                android.Manifest.permission.GET_TASKS,
                android.Manifest.permission.CAMERA,
                android.Manifest.permission.VIBRATE,
                android.Manifest.permission.ACCESS_WIFI_STATE,
                android.Manifest.permission.ACCESS_NETWORK_STATE,
        };
        ActivityCompat.requestPermissions(this, permission, 0);
    }

答案 1 :(得分:0)

1. need write permission in mainfest
       // retrieving bitmap from imageview

2.         Bitmap b = newImageView.getDrawingCache();

3.        // writing image into MotiMave folder
        public  void saveFile(Bitmap b){
            try {

        File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/MotiMate/");

                        if (!storageDir.exists()) {
                            storageDir.mkdirs();
                        }

                        File imageFile = File.createTempFile(
                                String.valueOf(Calendar.getInstance().getTimeInMillis()),
                                ".jpeg",                     /* suffix */
                                storageDir                   /* directory */
                        );


             FileOutputStream writeStream = new FileOutputStream(imageFile);
                        Timber.d(">> writing images");
                        b.compress(Bitmap.CompressFormat.JPEG, 100, writeStream);
                        writeStream.flush();
                        writeStream.close();

                        addPicToGallery(imageFile);
                        Toast.makeText(this, R.string.image_save_msg, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();

                        Toast.makeText(this, R.string.image_save_error_msg, Toast.LENGTH_SHORT).show();
                    }
                }

4.    // scanning image in gallery
            public void addPicToGallery(File imageFile) 
            {
             Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

                    Uri contentUri = Uri.fromFile(imageFile);
                    mediaScanIntent.setData(contentUri);
                    sendBroadcast(mediaScanIntent);
            }