Android obtains images from album,

Source: Internet
Author: User

Android obtains images from album,

In applications, you may often need to go to the album to obtain images. Every time you forget it, make a record for future reference.

To obtain images from an app album, follow these steps:

1. Set intent to call the system album

2. Select an image from the album. If the album does not have a satisfactory image, you can use the camera to take a photo and finally return the data to the application.

3. After the application obtains the image, it calls the cropping program to crop the image.

4. Return and display the cropped Image

 

1. Set intent to call the system album and go to the album to select an image

/*** Call album */private void goAlbums () {Intent intent = new Intent (Intent. ACTION_GET_CONTENT); intent. addCategory (Intent. CATEGORY_OPENABLE); intent. setType ("image/*"); startActivityForResult (intent, SELECT_PIC );}

Use the above settings to go to the album. The returned image data is processed by the onActivityResult method of the Activity. The request code is SELECT_PIC and the request code is int type. You can set it as needed.

After obtaining the returned image, the following steps are taken:

 

Ii. Call the cropping program to crop images

/*** Crop a large image * @ param context * @ param uri */private void clipperBigPic (Context context, Uri uri) {if (null = uri) {return ;} intent intent = new Intent ("com. android. camera. action. CROP "); if (Build. VERSION. SDK_INT> = Build. VERSION_CODES.KITKAT) {String url = PhotoClipperUtil. getPath (context, uri); intent. setDataAndType (Uri. fromFile (new File (url), "image/*");} // send the cropping command intent. putExtra ("crop", true); // intent in the X direction. putExtra ("aspectX", 1); // proportion intent in the Y direction. putExtra ("aspectY", 1); // specifies the width of intent in the cropping area. putExtra ("outputX", 124); // specifies the high intent of the cropping area. putExtra ("outputY", 124); // whether to retain the intent ratio. putExtra ("scale", true); // The returned data intent. putExtra ("return-data", true); // output image format intent. putExtra ("outputFormat", Bitmap. compressFormat. PNG. toString (); // specifies the position where the cropped image is saved, intent. putExtra (MediaStore. EXTRA_OUTPUT, getTempUri (); startActivityForResult (intent, SELECT_CLIPPER_PIC );}

In the above Code, Build. VERSION. SDK_INT> = Build. VERSION_CODES.KITKAT is returned because the data returned by KITKAT or a later VERSION may be different from the data of a later VERSION of KITKAT and needs to be processed separately.

The following code is normal processing. Set the cropping parameters. The request data is also handled by onActivityResult.

GetTempUri is used to set the temporary image storage directory. The Code is as follows:

Private Uri getTempUri () {return Uri. fromFile (getTempFile ();}/*** temporary image storage path * @ return */private File getTempFile () {File file File = new File (Environment. getExternalStorageDirectory (), IMAGE_FILE_NAME); try {file. createNewFile ();} catch (IOException e) {e. printStackTrace ();} return file ;}

In the above Code, IMAGE_FILE_NAME needs to be specified by yourself

The PhotoClipperUtil class code in the above Code is as follows:

package tmg.gotoalarm;import android.annotation.SuppressLint;import android.content.ContentUris;import android.content.Context;import android.database.Cursor;import android.net.Uri;import android.os.Build;import android.os.Environment;import android.provider.DocumentsContract;import android.provider.MediaStore;public class PhotoClipperUtil {    @SuppressLint("NewApi")    public static String getPath(final Context context, final Uri uri) {        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;        // DocumentProvider        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {            // ExternalStorageProvider            if (isExternalStorageDocument(uri)) {                final String docId = DocumentsContract.getDocumentId(uri);                final String[] split = docId.split(":");                final String type = split[0];                if ("primary".equalsIgnoreCase(type)) {                    return Environment.getExternalStorageDirectory() + "/" + split[1];                }            }            // DownloadsProvider            else if (isDownloadsDocument(uri)) {                final String id = DocumentsContract.getDocumentId(uri);                final Uri contentUri = ContentUris.withAppendedId(                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));                return getDataColumn(context, contentUri, null, null);            }            // MediaProvider            else if (isMediaDocument(uri)) {                final String docId = DocumentsContract.getDocumentId(uri);                final String[] split = docId.split(":");                final String type = split[0];                Uri contentUri = null;                if ("image".equals(type)) {                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;                } else if ("video".equals(type)) {                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;                } else if ("audio".equals(type)) {                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;                }                final String selection = "_id=?";                final String[] selectionArgs = new String[] {                        split[1]                };                return getDataColumn(context, contentUri, selection, selectionArgs);            }        }        // MediaStore (and general)        else if ("content".equalsIgnoreCase(uri.getScheme())) {            // Return the remote address            if (isGooglePhotosUri(uri))                return uri.getLastPathSegment();            return getDataColumn(context, uri, null, null);        }        // File        else if ("file".equalsIgnoreCase(uri.getScheme())) {            return uri.getPath();        }        return null;    }    /**     * Get the value of the data column for this Uri. This is useful for     * MediaStore Uris, and other file-based ContentProviders.     *     * @param context The context.     * @param uri The Uri to query.     * @param selection (Optional) Filter used in the query.     * @param selectionArgs (Optional) Selection arguments used in the query.     * @return The value of the _data column, which is typically a file path.     */    public static String getDataColumn(Context context, Uri uri, String selection,                                       String[] selectionArgs) {        Cursor cursor = null;        final String column = "_data";        final String[] projection = {                column        };        try {            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,                    null);            if (cursor != null && cursor.moveToFirst()) {                final int index = cursor.getColumnIndexOrThrow(column);                return cursor.getString(index);            }        } finally {            if (cursor != null)                cursor.close();        }        return null;    }    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is ExternalStorageProvider.     */    public static boolean isExternalStorageDocument(Uri uri) {        return "com.android.externalstorage.documents".equals(uri.getAuthority());    }    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is DownloadsProvider.     */    public static boolean isDownloadsDocument(Uri uri) {        return "com.android.providers.downloads.documents".equals(uri.getAuthority());    }    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is MediaProvider.     */    public static boolean isMediaDocument(Uri uri) {        return "com.android.providers.media.documents".equals(uri.getAuthority());    }    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is Google Photos.     */    public static boolean isGooglePhotosUri(Uri uri) {        return "com.google.android.apps.photos.content".equals(uri.getAuthority());    }}

The process for obtaining album images is as follows:

MGoAlarmIv. setOnClickListener (new View. OnClickListener () {@ Override public void onClick (View v) {// call the system album to go to the album to get the image goAlbums ();}});

After entering the album, the transfer of the application is handled by onActivityResult.

@ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onActivityResult (requestCode, resultCode, data); if (data = null) {return;} switch (requestCode) {case SELECT_PIC: // crop the clipperBigPic (this, data. getData (); break; case SELECT_CLIPPER_PIC: // Save the image to a local device after obtaining the image. Whether to save the image depends on the situation ); // display image showImage (mGoAlarmIv); break ;}}

The code for saving the image is as follows:

/*** Save the image * @ param data */private void saveBitmap (Intent data) {Bundle bundle = data. getExtras (); if (bundle! = Null) {Bitmap bitmap = bundle. getParcelable ("data"); File file = new File (Environment. getExternalStorageDirectory (), IMAGE_FILE_NAME); try {file. createNewFile (); FileOutputStream fileOutputStream = new FileOutputStream (file); bitmap. compress (Bitmap. compressFormat. PNG, 100, fileOutputStream); fileOutputStream. flush (); fileOutputStream. close ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}

OK. The above is the entire process for a third-party application to call the album to obtain images.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.