Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to take pictures and take out photo albums by android

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "how android takes pictures and takes out photo albums". The content is easy to understand and clear. I hope it can help you solve your doubts. Let the editor lead you to study and learn the article "how to take pictures and take out photo albums in android".

Create a xml layout file (activity_main.xml): two Button buttons in the head, one to control the selection of photos from the album, and one control to start the album to take pictures and select pictures. At the bottom is an ImageVIew that shows the image you just selected.

Before the Android 4.4 system, if you need to declare the permission to access the application associated directory of the SD card, the permission declaration is no longer required. The relevant permissions become dynamic applications.

The first part: take pictures and get pictures.

We put the photos in the SD card associated cache directory. Call the getExternalCacheDir () method to get the associated cache directory, the specific path is / sdcard/Android/data//cache. So why use the application-associated cache directory to store pictures? Because reading and writing SD cards are listed as dangerous permissions from Android 6.0system, if you store pictures in any other directory of SD cards, you have to deal with run-time permissions and use application association.

Directories can skip this step.

* take pictures or get pictures from albums * / public class MainActivity extends AppCompatActivity {private Button btn_camera; private ImageView imageView; public static final int TAKE_CAMERA = 101; private Uri imageUri; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); btn_camera = (Button) findViewById (R.id.btn_camera); imageView = (ImageView) findViewById (R.id.image_show) / / take btn_camera.setOnClickListener through the camera (new View.OnClickListener () {@ Override public void onClick (View v) {/ / create a File object to store the photographed image / / store it in the associated cache directory of the mobile SD card application File outputImage = new File (getExternalCacheDir (), "output_image.jpg") / * starting from the Android 6.0system, reading and writing SD cards are listed as dangerous permissions. If you store pictures in any other directory of the SD card, you need run-time permission processing, and you can skip this step by using the application-associated directory * / try {if (outputImage.exists ()) {outputImage.delete ();}} catch (Exception e) {e.printStackTrace () } / * 7. 0 system, Uri that directly uses the local real path is considered unsafe, and a FileUriExposedException exception will be thrown. FileProvider, on the other hand, is a special content provider, which uses a mechanism similar to the content provider to protect data, and can optionally share encapsulated Uri to the outside world. As a result, the security of the application is improved * / if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.N) {/ / greater than or equal to version 24 (7.0) imageUri = FileProvider.getUriForFile (MainActivity.this, "com.feige.pickphoto.fileprovider", outputImage) } else {/ / less than android version 7.0th (24) imageUri = Uri.fromFile (outputImage);} / start the camera program Intent intent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE); / / MediaStore.ACTION_IMAGE_CAPTURE = android.media.action.IMAGE_CAPTURE intent.putExtra (MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult (intent, TAKE_CAMERA);}}) @ Override protected void onActivityResult (int requestCode, int resultCode, @ Nullable Intent data) {switch (requestCode) {case TAKE_CAMERA: if (resultCode = = RESULT_OK) {try {/ / display the photos taken Bitmap bitmap = BitmapFactory.decodeStream (getContentResolver (). OpenInputStream (imageUri)); imageView.setImageBitmap (bitmap);} catch (FileNotFoundException e) {e.printStackTrace ();}} break; default: break;}

Starting with Android 7. 0, a Uri that directly uses a local real path is considered insecure and a FileUriExposedException exception is thrown. FileProvider is a special content provider, which uses a mechanism similar to the content provider to protect data, and can selectively share the encapsulated Uri to the outside, thus improving the security of the application.

The first step is to register the content provider in AndroidManifest.xml:

Create a file_paths resource file: right-click-- > new-- > Directory on the res directory to create a xml folder, and then create a new file_paths.xml file in the xml folder:

Part two: get pictures from photo albums

/ * take pictures or get pictures from albums * / public class MainActivity extends AppCompatActivity {private Button choose_photo; private ImageView imageView; public static final int PICK_PHOTO = 102; private Uri imageUri; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); choose_photo = (Button) findViewById (R.id.btn_photo); imageView = (ImageView) findViewById (R.id.image_show) / / Select picture choose_photo.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v)) {/ / dynamically apply for access to read / write disk if (ContextCompat.checkSelfPermission (MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)! = PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions (MainActivity.this, new String [] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101) } else {/ / Open album Intent intent = new Intent (Intent.ACTION_GET_CONTENT); / / Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT" intent.setType ("image/*"); startActivityForResult (intent, PICK_PHOTO); / / Open album}) } @ Override protected void onActivityResult (int requestCode, int resultCode, @ Nullable Intent data) {switch (requestCode) {case PICK_PHOTO: if (resultCode = = RESULT_OK) {/ / determine the mobile system version number if (Build.VERSION.SDK_INT > = 19) {/ / 4.4 and above use this method to process pictures handleImageOnKitKat (data);} else {/ / 4.4 systems use this method to process pictures handleImageBeforeKitKat (data) } break; default: break;} @ TargetApi (19) private void handleImageOnKitKat (Intent data) {String imagePath = null; Uri uri = data.getData (); if (DocumentsContract.isDocumentUri (this, uri)) {/ / if it is a Uri of type document, String docId = DocumentsContract.getDocumentId (uri) is processed through document id; if ("com.android.providers.media.documents" .equals (uri.getAuthority () {String id = docId.split (":") [1] / parse id String selection = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);} else if ("com.android.providers.downloads.documents" .equals (uri.getAuthority () {Uri contentUri = ContentUris.withAppendedId (Uri.parse ("content: / / downloads/public_downloads"), Long.valueOf (docId)); imagePath = getImagePath (contentUri, null) }} else if ("content" .equalsIgnoreCase (uri.getScheme () {/ / if it is a content type Uri, use the normal method to deal with imagePath = getImagePath (uri, null);} else if ("file" .equalsIgnoreCase (uri.getScheme () {/ / if it is a file type Uri, you can directly get the image path imagePath = uri.getPath ();} / / display the picture displayImage (imagePath) according to the picture path * @ param data * / private void handleImageBeforeKitKat (Intent data) {Uri uri = data.getData (); String imagePath = getImagePath (uri, null); displayImage (imagePath);} private String getImagePath (Uri uri, String selection) {String path = null; / / obtain the real image path Cursor cursor = getContentResolver () through Uri and selection. Query (uri, null, selection, null, null) If (cursor! = null) {if (cursor.moveToFirst ()) {path = cursor.getString (cursor.getColumnIndex (MediaStore.Images.Media.DATA));} cursor.close ();} return path;} private void displayImage (String imagePath) {if (imagePath! = null) {Bitmap bitmap = BitmapFactory.decodeFile (imagePath); imageView.setImageBitmap (bitmap);} else {Toast.makeText (this, "failed to get album pictures", Toast.LENGTH_SHORT). Show ();}

A FileProvider content provider that shares photos and takes pictures.

* complete MainActivity code:

Import android.Manifest;import android.annotation.TargetApi;import android.content.ContentUris;import android.content.Intent;import android.content.pm.PackageManager;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Build;import android.provider.DocumentsContract;import android.provider.MediaStore;import android.support.annotation.Nullable;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v4.content.FileProvider Import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import java.io.File;import java.io.FileNotFoundException; / * take pictures or get pictures from albums * / public class MainActivity extends AppCompatActivity {private Button choose_photo; private Button btn_camera; private ImageView imageView; public static final int TAKE_CAMERA = 101; public static final int PICK_PHOTO = 102; private Uri imageUri @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); choose_photo = (Button) findViewById (R.id.btn_photo); btn_camera = (Button) findViewById (R.id.btn_camera); imageView = (ImageView) findViewById (R.id.image_show) / / take btn_camera.setOnClickListener through the camera (new View.OnClickListener () {@ Override public void onClick (View v) {/ / create a File object to store the photographed image / / store it in the associated cache directory of the mobile SD card application File outputImage = new File (getExternalCacheDir (), "output_image.jpg") / * * starting from the Android 6.0system, reading and writing SD cards are listed as dangerous permissions. If you store pictures in any other directory of the SD card, * runtime permissions are required, and you can skip this step by using the application associated directory * / try {if (outputImage.exists ()) {outputImage.delete ();}} catch (Exception e) {e.printStackTrace () } / * 7.0 system, Uri that directly uses the local real path is considered unsafe, and a FileUriExposedException exception will be thrown. * FileProvider is a special content provider that uses a mechanism similar to the content provider to protect data. * encapsulated Uri can be selectively shared with the outside world. As a result, the security of the application is improved * / if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.N) {/ / greater than or equal to version 24 (7.0) imageUri = FileProvider.getUriForFile (MainActivity.this, "com.feige.pickphoto.fileprovider", outputImage) } else {/ / less than android version 7.0th (24) imageUri = Uri.fromFile (outputImage);} / start the camera program Intent intent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE); / / MediaStore.ACTION_IMAGE_CAPTURE = android.media.action.IMAGE_CAPTURE intent.putExtra (MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult (intent, TAKE_CAMERA);}}) / / Select picture choose_photo.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v)) {/ / dynamically apply for access to read / write disk if (ContextCompat.checkSelfPermission (MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)! = PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions (MainActivity.this, new String [] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101) } else {/ / Open album Intent intent = new Intent (Intent.ACTION_GET_CONTENT); / / Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT" intent.setType ("image/*"); startActivityForResult (intent, PICK_PHOTO); / / Open album}) } @ Override protected void onActivityResult (int requestCode, int resultCode, @ Nullable Intent data) {switch (requestCode) {case TAKE_CAMERA: if (resultCode = = RESULT_OK) {try {/ / display the photos taken Bitmap bitmap = BitmapFactory.decodeStream (getContentResolver (). OpenInputStream (imageUri)); imageView.setImageBitmap (bitmap);} catch (FileNotFoundException e) {e.printStackTrace ();}} break Case PICK_PHOTO: if (resultCode = = RESULT_OK) {/ / determine the mobile system version number if (Build.VERSION.SDK_INT > = 19) {/ / 4.4 and above use this method to process pictures handleImageOnKitKat (data);} else {/ / 4.4 systems use this method to process pictures handleImageBeforeKitKat (data);}} break; default: break;}} @ TargetApi (19) private void handleImageOnKitKat (Intent data) {String imagePath = null Uri uri = data.getData (); if (DocumentsContract.isDocumentUri (this, uri)) {/ / if it is a document type Uri, process String docId = DocumentsContract.getDocumentId (uri) through document id; if ("com.android.providers.media.documents" .equals (uri.getAuthority () {String id = docId.split (":") [1]; / / parse id String selection = MediaStore.Images.Media._ID + "=" + id in numeric format ImagePath = getImagePath (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);} else if ("com.android.providers.downloads.documents" .equals (uri.getAuthority () {Uri contentUri = ContentUris.withAppendedId (Uri.parse ("content: / / downloads/public_downloads"), Long.valueOf (docId)); imagePath = getImagePath (contentUri, null) }} else if ("content" .equalsIgnoreCase (uri.getScheme () {/ / if it is a content type Uri, use the normal method to deal with imagePath = getImagePath (uri, null);} else if ("file" .equalsIgnoreCase (uri.getScheme () {/ / if it is a file type Uri, you can directly get the image path imagePath = uri.getPath ();} / / display the picture displayImage (imagePath) according to the picture path * @ param data * / private void handleImageBeforeKitKat (Intent data) {Uri uri = data.getData (); String imagePath = getImagePath (uri, null); displayImage (imagePath);} private String getImagePath (Uri uri, String selection) {String path = null; / / obtain the real image path Cursor cursor = getContentResolver () through Uri and selection. Query (uri, null, selection, null, null) If (cursor! = null) {if (cursor.moveToFirst ()) {path = cursor.getString (cursor.getColumnIndex (MediaStore.Images.Media.DATA));} cursor.close ();} return path;} private void displayImage (String imagePath) {if (imagePath! = null) {Bitmap bitmap = BitmapFactory.decodeFile (imagePath); imageView.setImageBitmap (bitmap);} else {Toast.makeText (this, "failed to get picture", Toast.LENGTH_SHORT). Show () } the above is all the contents of the article "how to take pictures and take out photo albums by android". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report