How to save images in Android?

2019-09-16 20:04发布

问题:

I'm very new to Android programming and I was wondering how can I make an app take a picture and save the image to the internal storage of a device, not to the SD card, because not everyone will have an SD card.

回答1:

You can try saving it as an sqlite blob. This this thread for how to do the storage. Saying "not everyone will have external storage" is a bad excuse: you should handle both cases. If instead you want to implement it as a file (a perfectly good way to do it), you can look up an external storage directory using the Environment.getExternalStorageDir() call to determine a suitable directory in which to store your files. Read the API documentation here and heed the following note:

Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.



回答2:

Yes, you can try to save images in sqlite blob fields. It's just a java way: and let the whole world wait :)

It's a good practice to store all your files, cache etc into /Android/data/<package_name>/files/ directory on external storage. External storage is not the only SD cards and you can get external storage path and state by Environment.getExternalStorageDirectory() and Environment.getExternalStorageState() calls (reference). If you are using API 8 or greater, you can use Context.getExternalFilesDir().

If you would like to get user's hate-rays, you can try to store files and folders in the root of external storage.



回答3:

Perhaps something like this

 Bitmap largeBitmap ;  // save your Bitmap from data[]
 FileOutputStream fileOutputStream = null;
 BufferedOutputStream bos = null;
 int quality = 100;

 String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "myImage.jpg"

 File mediaFile = new File(filePath);

 try {

      fileOutputStream = new FileOutputStream(pictureFile);
      bos = new BufferedOutputStream(fileOutputStream);
      bitmap.compress(CompressFormat.JPEG, quality, bos);

      return pictureFile;
 } finally {
      if (bos != null) {
      try {
           bos.close();
      } catch (IOException e) {
      // ignore close error
      }
 }