Taking photos simply simple photo taking

Source: Internet
Author: User

Suppose you are implementing a crowd-sourced weather service that makes a global weather map by blending together pictures of the sky taken by devices running your client app. integrating photos is only a small part of your application. you want to take
Photos with minimal fuss, not reinvent the camera. happily, most Android-powered devices already have at least one camera application installed. in this lesson, you learn how to make it take a picture for you.

Http://blog.csdn.net/sergeycao

Request camera permission

If an essential function of your application is taking pictures, then restrict its visibility on Google Play to devices that have a camera. to advertise that your application depends on having a camera, put<uses-feature>Tag
In your manifest file:

<manifest ... >    <uses-feature android:name="android.hardware.camera" />    ...</manifest ... >

If your application uses, but does not require a camera in order to function, addandroid:required="false"To the tag. In doing so, Google Play will allow devices without a camera to download your application. It's then your responsibility
Check for the availability of the camera at runtime by callinghasSystemFeature(PackageManager.FEATURE_CAMERA). If a camera is not available, you shoshould then disable your camera features.

Take a photo with the camera app

The android way of delegating actions to other applications is to invoke
Intent
That describes what you want done. This process involves three pieces:IntentItself, a call to start the external
Activity, And some code to handle the image data when Focus returns to your activity.

Here's a function that invokes an intent to capture a photo.

private void dispatchTakePictureIntent(int actionCode) {    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);    startActivityForResult(takePictureIntent, actionCode);}

Congratulations: with this code, your application has gained the ability to make another camera application do its bidding! Of course, if no compatible application is ready to catch the intent, then your app will fall down like a botched Stage dive. Here
Is a function to check whether an app can handle your intent:

public static boolean isIntentAvailable(Context context, String action) {    final PackageManager packageManager = context.getPackageManager();    final Intent intent = new Intent(action);    List<ResolveInfo> list =            packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);    return list.size() > 0;}
View the photo

If the simple feat of taking a photo is not the culmination of your app's ambition, then you probably want to get the image back from the camera application and do something with it.

The android camera application encodes the photo in the returnIntentDeliveredonActivityResult()As a small
BitmapIn the extras, under the key"data". The following code retrieves this image and displays it inImageView.

private void handleSmallCameraPhoto(Intent intent) {    Bundle extras = intent.getExtras();    mImageBitmap = (Bitmap) extras.get("data");    mImageView.setImageBitmap(mImageBitmap);}

Note:This thumbnail image from"data"Might be good for an icon, but not a lot more. Dealing with a full-sized image takes a bit more work.

Save the photo

The android camera application saves a full-size photo if you give it a file to save into. You must provide a path that includes des the storage volume, folder, and file name.

There is an easy way to get the path for photos, but it works only on Android 2.2 (API Level 8) and later:

 storageDir = new File(    Environment.getExternalStoragePublicDirectory(        Environment.DIRECTORY_PICTURES    ),     getAlbumName());

For earlier API levels, you have to provide the name of the photo directory yourself.

 storageDir = new File (    Environment.getExternalStorageDirectory()        + PICTURES_DIR        + getAlbumName());

Note:The path componentPICTURES_DIRIs justPictures/, The standard location for shared photos on the external/shared storage.

Set the file name

As shown in the previous section, the file location for an image shoshould be driven by the device environment. what you need to do yourself is choose a collision-resistant file-naming scheme. you may wish also to save the path in a member variable for later
Use. Here's an example solution:

 private File createImageFile() throws IOException {    // Create an image file name    String timeStamp =         new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());    String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";    File image = File.createTempFile(        imageFileName,         JPEG_FILE_SUFFIX,         getAlbumDir()    );    mCurrentPhotoPath = image.getAbsolutePath();    return image;}
Append the file name onto the intent

Once you have a place to save your image, pass that location to the camera application viaIntent.

File f = createImageFile();takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Add the photo to a gallery

When you create a photo through an intent, you shoshould know where your image is located, because you said where to save it in the first place. for everyone else, perhaps the easiest way to make your photo accessible is to make it accessible from the system's
Media provider.

The following example method demonstrates how to invoke the system's media repository to add your photo the media provider's database, making it available in the android gallery application and to other apps.

private void galleryAddPic() {    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);    File f = new File(mCurrentPhotoPath);    Uri contentUri = Uri.fromFile(f);    mediaScanIntent.setData(contentUri);    this.sendBroadcast(mediaScanIntent);}
Decode a scaled Image

Managing multiple full-sized images can be tricky with limited memory. if you find your application running out of memory after displaying just a few images, You can dramatically reduce the amount of dynamic heap used by expanding the JPEG into a memory
Array that's already scaled to match the size of the destination view. The following example method demonstrates this technique.

private void setPic() {    // Get the dimensions of the View    int targetW = mImageView.getWidth();    int targetH = mImageView.getHeight();      // Get the dimensions of the bitmap    BitmapFactory.Options bmOptions = new BitmapFactory.Options();    bmOptions.inJustDecodeBounds = true;    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);    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;      Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);    mImageView.setImageBitmap(bitmap);}

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.