Code Xiaosheng, a technology platform focused on the Android field

Join my Android technology group

Author: xue tao links: https://www.jianshu.com/p/832d723039da disclaimer: this article has been published, it has been approved of xue tao forwarding, etc. Please contact the author authorization

Take advantage of the National Day we have time to talk about the most commonly used to select a user picture series of functions, go!

Results show effect display links to https://v.qq.com/x/page/r0735cdxorz.html

1. Selection of pictures

Taking pictures

EXTRA_OUTPUT (intent.putextra) : intent.putextra (MediaStore.EXTRA_OUTPUT) : intent.putextra PutExtra (Mediastore. EXTRA_OUTPUT) = intent.putextra (intent.putextra);

// The camera takes a picture of a symbol, followed by a TAKEPAHTO = 1; Intent Intent = new Intent(mediastore.action_image_capture); //7.0 set the url Uri norTakePhotoSaveAdr for saving images below; If (build.version.sdk_int >= build.version_codes.n) {// Temporarily add a photo permission intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); / / / / through FileProvider access to save the image file uri (create the file first, and then get the uri of the file) takePhotoSaveAdr = FileProvider. GetUriForFile (MainActivity. This,  "com.hxzk.bj.photodemo", new File(Environment.getExternalStorageDirectory(), "savephoto.jpg")); EXTRA_OUTPUT- This setting requires a Uri intent. PutExtra (mediastore. EXTRA_OUTPUT, takePhotoSaveAdr) to save the path and file name of the video. } else { norTakePhotoSaveAdr = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "savephoto.jpg")); intent.putExtra(MediaStore.EXTRA_OUTPUT, norTakePhotoSaveAdr); } //PHOTO_TAKEPHOTO (intent, PHOTO_TAKEPHOTO);Copy the code

Photo album

Compared to taking photos, album is a little simpler, code has annotations, directly look at:

// take a picture of a TAKEPAHTO = 0; // intent.action_pick = new Intent(intent.action_get_content); // Intent.action_pick = new Intent(intent.action_get_content); // Intent.action_get_content = new Intent(intent.action_get_content); //intent.setType("image/*"); // intent.setType("video/*"); //intent.setType("audio/*") = new intent (intent.action_pick); // intent.setType(ContactsContract.Contacts.CONTENT_TYPE); // startActivityForResult(intent, PICK_CONTACT); Intent = new Intent(intent.action_pick, null); // External is a multimedia file under sdcard, and Internal is a multimedia file under system. / / use INTERNAL_CONTENT_URI can only display is stored in the internal photos of intent. SetDataAndType (MediaStore. Images. Media. INTERNAL_CONTENT_URI, "image / *"); StartActivityForResult (intent, PHOTO_PHOTOALBUM);Copy the code

Click the return result of taking a photo or selecting an image

Whether we take a picture or select an image, we need to retrieve the result in the Activity’s onActivityResult and proceed to the next step. To mention, we have a requestCode for jumping albums or taking photos, as shown in startActivityForResult(Intent, PHOTO_PHOTOALBUM); For this, we have globally defined three, namely, photo taking, album, and cropped logo:

Private static final int PHOTO_PHOTOALBUM = 0; private static final int PHOTO_PHOTOALBUM = 0; Private static final int PHOTO_TAKEPHOTO = 1; // Clipping private static final int PHOTO_PHOTOCLIP = 2;Copy the code

This is used in onActivityResult:

image.png

Nothing to say!

2. Image cropping and compression

Image clipping (reduces the size of the image file in the phone (because clipping is only part), for example from 1m to 128KB)

Cropping of images let’s take a look at the cropping method starPhotoZoom (), the code is as follows:

public void startPhotoZoom(Uri uri) { Log.e("uri=====", "" + uri); / / com. Android. Camera. Action. CROP, this action is the image cutting function call system Intent Intent = new Intent (com. Android. Camera. The action. "CROP"); intent.setDataAndType(uri, "image/*"); // Crop the image uri and the image type intent. PutExtra ("crop", "true"); PutExtra ("crop", "circle") intent. PutExtra ("aspectX", 1); // Set crop" crop", "circle") intent. Intent. PutExtra ("aspectY", 1); Intent. PutExtra ("outputX", 60); // The size of X pixels when the data is returned. intent.putExtra("outputY", 60); // The Y pixel size when the data is returned. //uritempFile is a Uri class variable, Instantiate uritempFile if (build.version.sdk_int >= build.version_codes.n) {if (TAKEPAHTO == 1) {// If the photo is 7.0 // enable read and write permissions for temporary access intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); Intent.setclipdata (clipdata.newrawuri (mediastore. EXTRA_OUTPUT, uri)); uriClipUri = uri; } else {// set the cropped image address Uri uriClipUri = uri.parse ("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "clip.jpg"); } } else { uriClipUri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "clip.jpg"); } Log.e("uriClipUri=====", "" + uriClipUri); //Android limits the size of data that can be included in an Intent. Intent.putextra (Mediastore. EXTRA_OUTPUT, uriClipUri); intent.putextra (Intent.extra_output, uriClipUri); intent.putExtra("return-data", false); / / whether to keep the data returned in the Bitmap intent. PutExtra (" outputFormat ", Bitmap.Com pressFormat. JPEG. The toString ()); Intent. PutExtra ("noFaceDetection", true); StartActivityForResult (intent, PHOTO_PHOTOCLIP); // Clipping finished tag}Copy the code

Image compression (reduced bitmap size when images are loaded, avoiding oom, but images themselves remain the same size on the phone)

I’ll go straight to the method:

/ * * * the method of image compression (just memory decrease, avoid oom, picture itself in the disk plate volume) * display Bitmap memory a bit less, */ public void compressPhto(File mFile){// The BitmapFactory class provides several parsing methods (decodeResource, decodeStream, decodeFile, etc.) to create bitmaps. // For example, if the image is from the network, use decodeStream; // If it is a sd card image, you can choose decodeFile method; Bitmapfactory.options = new bitmapFactory.options (); options.inJustDecodeBounds = true; / / get the boundary of the current image size / / BitmapFactory decodeResource (getResources (), R.d rawable. The bg, options); BitmapFactory.decodeFile(mFile.getAbsolutePath(),options); int outHeight = options.outHeight; Int outWidth = options.outWidth; int outWidth = options.outWidth; String outMimeType = options.outMimeType; options.inJustDecodeBounds = false; //inSampleSize can be used to reduce the size of the image by a factor of inSampleSize. InSampleSize = caculateSampleSize(options, 500, 500); //etPath() returns the path when the file was constructed. GetAbsolutePath () returns the full path String path = mfile.getPath (); String absPath=mFile.getAbsolutePath(); Bitmap bitmap = BitmapFactory.decodeFile(absPath,options); ivUserPhoto.setImageBitmap(bitmap); Ivsie.setimagebitmap (bitmap); } @param options @param reqWidth @param reqHeight @param reqHeight @param reqHeight @param reqHeight @param reqHeight @param reqHeight @param reqHeight @return */ private int caculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { int sampleSize = 1; int picWidth = options.outWidth; int picHeight = options.outHeight; if (picWidth > reqWidth || picHeight > reqHeight) { int halfPicWidth = picWidth / 2; int halfPicHeight = picHeight / 2; while (halfPicWidth / sampleSize > reqWidth || halfPicHeight / sampleSize > reqHeight) { sampleSize *= 2; } } return sampleSize; }Copy the code

3. Picture adaptation

7.0 Adaptation Problems

I don’t know. Did you notice this code in the clipping method?

image.png

And the code for taking the photo:

image.png

Why did you write that? 7.0 the original version, we just call camera images to obtain the address is: file:///storage/emulated/0/temp.jpg file but then becomes: 7.0 the content: / /… File, using content:// instead of file:///. This is because Android has been passing file:// uris of type :// since 7.0 will trigger FileUriExposedException. Therefore, you must use the FileProvider when sharing private files.

Add FileProvider to the manifest file if an error is reported using the previous method:

image.png

What do we have in provider_Paths?

image.png

It’s in the notes. No, just change careers.

Cut to complete

Load images directly for display

image.png

4. Uploading pictures

To upload pictures

But there are also cases where we want to upload the loaded image, and I also provide you with a method:

Bitmap photoBitmap; File file; Public void upDateFile() {try {// photoBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uriClipUri)); } catch (FileNotFoundException e) { e.printStackTrace(); } / / create a path String path = Environment. External.getexternalstoragedirectory () getPath () + "/ Pic"; // Obtain external storage directory file = new file (path); // Create a new directory, the directory specified by this abstract pathname, including a required but nonexistent parent directory. file.mkdirs(); // Rename the file with the current time long time = system.currentTimemillis (); File = new file (file.tostring () + "/" + time+ ".png"); OutputStream out = null; try { out = new FileOutputStream(file.getPath()); } catch (FileNotFoundException e) { e.printStackTrace(); } / / compressed file, returns as a result, the true that successful Boolean bCompress = photoBitmap.com press (Bitmap.Com pressFormat. JPEG, 100, out); }Copy the code

5. Other knowledge

  • Clicking on the user’s avatar popover is not our usual PupUpWindow, but a custom BottomSheetDialog(to be optimized).

  • I have rounded the user profile picture, and this is also a custom ImageView, you can download the source code.

So much for the time being, later supplement!

Making the address https://github.com/searchdingding/PhotoDemo

I’m serious about sharing technology