简体   繁体   中英

Android ,What Is The Best way to store image to SQLite database , and retreive image from db?

iam new in android , I have an application that display images from Gallery Using Uri , and Display Images Using Bitmap , But Some Times The Images Loaded Slowly and if I Scrolling The App Hanging Although i use standard of converting Uri By Bitmap As Follow :

public static Bitmap getBitmapFromUri(Uri uri ,Context context,ImageView imageView) {

        if (uri == null || uri.toString().isEmpty())
            return null;

        // Get the dimensions of the View
        int targetW = imageView.getWidth();
        int targetH = imageView.getHeight();

        InputStream input = null;
        try {
            input = context.getContentResolver().openInputStream(uri);

            // Get the dimensions of the bitmap
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(input, null, bmOptions);
            input.close();

            int photoW = bmOptions.outWidth;
            int photoH = bmOptions.outHeight;

            // Determine how much to scale down the image
            int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

            // Decode the image file into a Bitmap sized to fill the View
            bmOptions.inJustDecodeBounds = false;
            bmOptions.inSampleSize = scaleFactor;
            bmOptions.inPurgeable = true;

            input = context.getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
            input.close();
            return bitmap;

        } catch (FileNotFoundException fne) {
            Log.e(LOG_TAG, "Failed to load image.", fne);
            return null;
        } catch (Exception e) {
            Log.e(LOG_TAG, "Failed to load image.", e);
            return null;
        } finally {
            try {
                input.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

Calling This Method As Follows

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // Receive the request code if match the product request id start get the image Uri
        if (PICK_PRODUCT_IMAGE == requestCode) {
            if (data != null) {
                imageUri = data.getData();

                getContentResolver().takePersistableUriPermission(imageUri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
                /**
                 * Start Set The Image Bitmap By Uri Of the Image
                 * Using {@link UploadImageBitmap#convertImageUriByBitmap(Uri, Context)}  }
                 */
                  //      productImageView.setImageBitmap(UploadImageBitmap.getBitmapFromUri(imageUri, getApplicationContext(),productImageView));

              productImageView.setImageBitmap(UploadImageBitmap.convertImageUriByBitmap(imageUri, this));

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

Is Store Uri and Display Images Using it slower than Store The Image In The Database and Display It Directly , Or I Use Wrong Way To Display Images from gallery or folders ? is There Better way to display images from gallery and database with better performance?

It depends on your apps need for security and whether the images should be local only or remote.

You can upload to S3 and then store the url in your Database You can store in mediaStore aka gallery and call the appropriate intents to refresh the gallery as it won't be default rescan, so you have to force a rescan of that file name to add it to the gallery like:

 MediaScannerConnection.scanFile(this, new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
        /*
         *   (non-Javadoc)
         * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
         */
        public void onScanCompleted(String path, Uri uri) 
          {
              Log.i("ExternalStorage", "Scanned " + path + ":");
              Log.i("ExternalStorage", "-> uri=" + uri);
          }
        });

Or you can just save the image to your own private app dir and just store the URI in your database.

The problem with storing in public gallery is that the user can delete it. If they delete it and your app loads URIs from your local SQLite and they are missing this will have to be handled as well. Unless you store only in private directory.

My preferred way is "if it is for my app only" then store in private directory for the app, and store URI in the database with the model in a row. If it needs to work on other devices then I upload to S3. If it needs to be accessible from gallery then I add to gallery and rescan. But no matter which direction you go, you still just store the URI or URL to the image.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM