Save image on external Storage

坚强是说给别人听的谎言 提交于 2019-12-11 07:57:34

问题


Hey I want to save an image in the external storage. I got two versions out of here but both aren't working. Goal is that the user clicks a button and the image is saved and then the user can also see it in the gallery. So here is Version one:

            String path = Environment.getExternalStorageDirectory().getPath();
            File outputDir= new File(path);
            outputDir.mkdirs();
            File newFile = new File(path+"/"+"test.png");
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(newFile);
                mutableBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

And this is Version 2:

            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "MyApplication";
            File outputDir= new File(path);
            outputDir.mkdirs();
            File newFile = new File(path+"/"+"test.png");
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(newFile);
                mutableBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

Thanks for help


回答1:


Try this

 AsyncTask fileTask = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] objects) {
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "MyApplication");
if (!directory.exists()) {
                    directory.mkdirs();
                }
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String name = " "+n+".jpg";
File pictureFile = new File(directory, name);
pictureFile.createNewFile();
try {
FileOutputStream out = new FileOutputStream(pictureFile);
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
       out.close();
} catch (Exception e) {
       e.printStackTrace();
}
return null;
        }
    };
    fileTask.execute();

This should work fine provided all the file handling permissions are available for your app.

Also please note that you should never do file operations in the main thread thus always use AsyncTask if you haven't already done so.




回答2:


Late but might be helpful

private void saveimage(Bitmap img) {


                try {
                    String imageName = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
                    boolean imageSaved = false;
                    if (!(img == null || img.isRecycled())) {
                        ContentResolver contentResolver = getContentResolver();
                        File file = new File(getStoragePath() + "img path/");
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        File imageFile = new File(file, String.format("%s.png", new Object[]{imageName}));
                        try {
                            FileOutputStream out = new FileOutputStream(imageFile);
                            imageSaved = img.compress(CompressFormat.PNG, 100, out);
                            if (out != null) {
                                out.flush();
                                out.close();
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "Unable to write the image to gallery", e);
                        }
                        ContentValues values = new ContentValues(8);
                        values.put(SettingsJsonConstants.PROMPT_TITLE_KEY, imageName);
                        values.put("_display_name", camera.name);
                        String location = "";
                        if (camera.country != null && camera.country.length() > 0) {
                            location = camera.country;
                        }
                        if (camera.city != null && camera.city.length() > 0) {
                            location = location + ", " + camera.city;
                        }
                        values.put("description", location);
                        values.put("mime_type", "image/png");
                        values.put("description", "");
                        long millis = System.currentTimeMillis();
                        values.put("date_added", Long.valueOf(millis / 1000));
                        values.put("datetaken", Long.valueOf(millis));
                        values.put("_data", imageFile.getAbsolutePath());
                        contentResolver.insert(Media.EXTERNAL_CONTENT_URI, values);
                        MediaScannerConnection.scanFile(getApplicationContext(), new String[]{imageFile.getPath()}, new String[]{"image/png"}, new OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                            }
                        });
                    }
                    if (imageSaved) {

                    }
                } catch (Exception e2) {
                    Log.e(TAG, "saveSnapshot", e2);
                }




    }


来源:https://stackoverflow.com/questions/41648947/save-image-on-external-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!