"Android App Development technology: Media development" photo shoot

Source: Internet
Author: User

Guo Xiaoxing
Weibo: Guo Xiaoxing's Sina Weibo
Email:[email protected]
Blog: http://blog.csdn.net/allenwells
Github:https://github.com/allenwells

A photo-enabled

Requesting Camera access

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

If our app uses a camera, but the camera is not a necessary component for the app to function properly, you can set the android:required to "false". That way, Google play will also allow devices without a camera to download the app. Of course we need to use the following methods:

hasSystemFeature(PackageManager.FEATURE_CAMERA);

To check if there is a camera on the device. If not, you should disable the camera-related features.

Using a Intent object that describes what to do, Android can delegate certain execution tasks to other applications. The whole process consists of three parts:

    • Intent itself
    • A function call to start the external activity
    • When the focus returns to our activity, the code that returns the image data is processed.

Example

Capture the photo by sending a intent, as shown below:

staticfinalint1;privatevoiddispatchTakePictureIntent(){    new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//在调用startActivityForResult()方法之前,先调用resolveActivity(),这个方法会返回能处理该Intent的第一个Activity,即检查有没有能处理这个Intent的Activity。执行这个检查非常重要,因为如果调用startActivityForResult()时,没有应用能处理Intent,那么应用将会崩溃。所以只要返回结果不为null,使用该Intent就是安全的。    ifnull)    {        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);    }}
Two saved photos 2.1 get thumbnail image

The Android camera app encodes the shot into a reduced bitmap, adds the extra value to the returned intent, and transmits it to Onactivityresult ()), and the corresponding key is data.

Example

Take this picture and display it on the ImageView as follows:

@OverrideprotectedvoidonActivityResult(intint resultCode, Intent data) {    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {        Bundle extras = data.getExtras();        Bitmap imageBitmap = (Bitmap) extras.get("data");        mImageView.setImageBitmap(imageBitmap);    }}
2.2 Getting full-size photos

If we provide a file object to the Android camera program, it will save this full-size photo under the given path. At this point we need to provide the file name that contains the suffix name that is required to store the image.

In general, any photos taken by the user using the device's camera should be stored in the public external storage of the device so that they can be accessed by all images. Pass Directory_pictures as an argument to the Getexternalstoragepublicdirectory ()) method to return the directory that is appropriate for storing the public picture. Because the directory provided by this method is shared by all applications, Read_external_storage and Write_external_storage permissions are required for read and write operations on the directory. Also, because write permissions imply Read permissions, if you need write permissions for external storage, you only need to request a permission, as follows:

...>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    ...</manifest>

However, if you want the photos to be private to our app, we can use the directory provided by Getexternalfilesdir (). In Android 4.3 and the following versions of the system, write this directory requires Write_external_storage permissions. Starting with Android 4.4, the directory will not be accessible to other apps, so this permission is no longer needed, and you can claim this permission only on the lower version of the Android device by adding the Maxsdkversion property, as follows:

...>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"                     android:maxSdkVersion="18" />    ...</manifest>

Once you have selected the directory where the files are stored, we need to design a naming convention that ensures that file names do not conflict. Sometimes the path is stored in a member variable for future use, as follows:

Timestamp as the file name

StringMcurrentphotopath;PrivateFile Createimagefile () throws IOException {//Create an image file name    StringTimeStamp= NewSimpleDateFormat ("Yyyymmdd_hhmmss").FormatNew Date());StringImagefilename= "Jpeg_" +TimeStamp+ "_"; File Storagedir=Environment.Getexternalstoragepublicdirectory (Environment.Directory_pictures); File image=File.Createtempfile (Imagefilename,/ * prefix * /        ". jpg",/ * suffix * /Storagedir/ * Directory * /);//Save a File:PATH for use with Action_view intentsMcurrentphotopath= "File:" +Image.GetAbsolutePath ();returnImage;}

With the above method, we can create a file object for the new photo, as follows:

Static Final intRequest_take_photo =1;Private void dispatchtakepictureintent() {Intent takepictureintent =NewIntent (mediastore.action_image_capture);//Ensure that there's a camera activity to handle the intent    if(Takepictureintent.resolveactivity (Getpackagemanager ())! =NULL) {//Create the File where the photo should goFile Photofile =NULL;Try{photofile = Createimagefile (); }Catch(IOException ex) {//Error occurred while creating the File...        }//Continue only if the File is successfully created        if(Photofile! =NULL) {Takepictureintent.putextra (Mediastore.extra_output, Uri.fromfile (photofile));        Startactivityforresult (Takepictureintent, Request_take_photo); }    }}
2.3 Adding photos to albums

When a photo is created through intent, we know where the picture is stored. But for others, the simplest way to view a photo is through the system's media Provider. Also, if we store the images in a directory provided by Getexternalfilesdir (), the media scanner is not accessible to our files because they belong to your app's private data.

Example

The media scanner that triggered the system adds the photos to the media provider database, which allows the Android album program and other programs to read the photos.

privatevoidgalleryAddPic() {    new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);    new File(mCurrentPhotoPath);    Uri contentUri = Uri.fromFile(f);    mediaScanIntent.setData(contentUri);    this.sendBroadcast(mediaScanIntent);}
Three decoded thumbnail photos

Managing many full-size images in limited memory can be tricky. Because it consumes a lot of memory, the solution is to significantly reduce memory usage by scaling the image to the target view size and then loading it into memory, as follows:

Private void Setpic() {//Get The dimensions of the View    intTARGETW = Mimageview.getwidth ();intTargeth = Mimageview.getheight ();//Get The dimensions of the bitmapBitmapfactory.options bmoptions =NewBitmapfactory.options (); Bmoptions.injustdecodebounds =true; Bitmapfactory.decodefile (Mcurrentphotopath, bmoptions);intPhotow = Bmoptions.outwidth;intPhotoh = Bmoptions.outheight;//Determine how much the image    intScalefactor = Math.min (PHOTOW/TARGETW, Photoh/targeth);//Decode the image file into a Bitmap sized to fill the ViewBmoptions.injustdecodebounds =false;    Bmoptions.insamplesize = Scalefactor; Bmoptions.inpurgeable =true;    Bitmap Bitmap = Bitmapfactory.decodefile (Mcurrentphotopath, bmoptions); Mimageview.setimagebitmap (bitmap);}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android App Development technology: Media development" photo shoot

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.