Android get local album pictures, take photos to get pictures

Source: Internet
Author: User

need: find pictures from a local photo album, or take pictures by calling the system camera.

Error-Prone areas:

1, when we specify the URI path of the photo, we cannot get the URI by Data.getdata (), but we should get the URI directly (in global variable or otherwise) and set it to ImageView

Imageview.setimageuri (URI);

2, I found the phone front camera shot out of only hundreds of KB, directly with Imageview.setimageuri (URI); there is no big problem, but the rear camera shot out of the larger picture, this time using Imageview.setimageuri (URI ), it is easy to get out of memory (OOM) error, we need to first convert the URI to bitmap, then compress Bitmap, and then through Imageview.setimagebitmap (bitmap), to display the picture.

3. Once the photos are stored in the SD card, the photos will not appear in the system album immediately, so we need to send a broadcast to remind the album to update the photos.

4, the use of sharepreference here, you should be careful to remove the cache after the end.

Code:

Mainactivity:

Package com.sctu.edu.test;

Import android.content.Intent;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.net.Uri;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.provider.MediaStore;
Import android.support.v7.app.AppCompatActivity;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.ImageView;

Import Com.sctu.edu.test.tools.ImageTools;

Import Java.io.File;
Import java.io.IOException;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;

public class Mainactivity extends Appcompatactivity {

private static final int photo_from_gallery = 1;
private static final int photo_from_camera = 2;
Private ImageView ImageView;
Private File Appdir;
Private Uri Uriforcamera;
private date date;
Private String str = "";
Private Sharepreference sharepreference;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Android does not recommend using global variables, I use sharepreference here
Sharepreference = Sharepreference.getinstance (this);
ImageView = (ImageView) Findviewbyid (R.id.imageview);
}

Take pictures from albums
public void Gallery (view view) {
Intent Intent = new Intent ();
Intent.settype ("image/*");
Intent.setaction (intent.action_get_content);
Startactivityforresult (Intent, photo_from_gallery);
}

Take pictures
public void camera (view view) {
Intent Intent = new Intent (mediastore.action_image_capture);

Uriforcamera = Uri.fromfile (Createimagestoragepath ());
Sharepreference.setcache ("uri", String.valueof (Uriforcamera));

/**
* URI path specified, Startactivityforresult does not return intent,
* So the URI cannot be obtained by Data.getdata () in Onactivityresult ();
*/
Intent.putextra (Mediastore.extra_output, Uriforcamera);
Startactivityforresult (Intent, Photo_from_camera);
}

@Override
protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
Super.onactivityresult (Requestcode, ResultCode, data);
First Level switch
Switch (requestcode) {
Case Photo_from_gallery:
Second Level switch
Switch (ResultCode) {
Case RESULT_OK:
if (data! = NULL) {
Uri uri = Data.getdata ();
Imageview.setimageuri (URI);
}
Break
Case result_canceled:
Break
}
Break
Case Photo_from_camera:
if (ResultCode = = RESULT_OK) {
Uri uri = Uri.parse (sharepreference.getstring ("uri"));
Updatedcim (URI);
try {
Convert URI to bitmap and compress bitmap to prevent oom (out of memory)
Bitmap Bitmap = Imagetools.getbitmapfromuri (URI, this);
Imageview.setimagebitmap (bitmap);
} catch (IOException e) {
E.printstacktrace ();
}

RemoveCache ("uri");
} else {
LOG.E ("Result", "is not OK" + resultcode);
}
Break
Default
Break
}
}

/**
* Set photo storage path, first store the photos in SD card, then operate
*
* @return
*/
Private File Createimagestoragepath () {
if (Hassdcard ()) {
Appdir = new File ("/sdcard/testimage/");
if (!appdir.exists ()) {
Appdir.mkdirs ();
}
SimpleDateFormat SimpleDateFormat = new SimpleDateFormat ("Yyyymmddhhmmss");
Date = new Date ();
str = Simpledateformat.format (date);
String fileName = str + ". jpg";
File File = new file (Appdir, fileName);
return file;
} else {
LOG.E ("SD", "is not load");
return null;
}
}

/**
* Insert photo into System album, remind album update
*
* @param URI
*/
private void Updatedcim (Uri uri) {
Intent Intent = new Intent (intent.action_media_scanner_scan_file);
Intent.setdata (URI);
This.sendbroadcast (Intent);

Bitmap Bitmap = Bitmapfactory.decodefile (Uri.getpath ());
MediaStore.Images.Media.insertImage (Getcontentresolver (), Bitmap, "", "" ");
}

/**
* Determine if the SD card is available
*
* @return
*/
Private Boolean Hassdcard () {
if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {
return true;
} else {
return false;
}
}

/**
* Remove Cache
*
* @param cache
*/
private void RemoveCache (String cache) {
if (Sharepreference.ifhaveshare (cache)) {
Sharepreference.removeonecache (cache);
} else {
LOG.E ("This cache", "was not exist.");
}
}

}


Imagetools:
Package com.sctu.edu.test.tools;

Import android.app.Activity;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.net.Uri;

Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException;
Import Java.io.InputStream;

public class Imagetools {

/**
* Get pictures and compress them by URI
*
* @param URI
* @param activity
* @return
* @throws IOException
*/
public static Bitmap Getbitmapfromuri (URI Uri, activity activity) throws IOException {
InputStream InputStream = Activity.getcontentresolver (). Openinputstream (URI);
Bitmapfactory.options Options = new Bitmapfactory.options ();
Options.injustdecodebounds = true;
Options.indither = true;
Options.inpreferredconfig = Bitmap.Config.ARGB_8888;
Bitmapfactory.decodestream (InputStream, NULL, options);
Inputstream.close ();

int originalwidth = Options.outwidth;
int originalheight = Options.outheight;
if (OriginalWidth = =-1 | | originalheight = =-1) {
return null;
}

float height = 800f;
float width = 480f;
int be = 1; Be=1 indicates no scaling
if (OriginalWidth > OriginalHeight && originalwidth > width) {
be = (int) (originalwidth/width);
} else if (OriginalWidth < originalheight && originalheight > height) {
be = (int) (originalheight/height);
}

if (be <= 0) {
be = 1;
}
Bitmapfactory.options Bitmapoptinos = new Bitmapfactory.options ();
Bitmapoptinos.insamplesize = be;
Bitmapoptinos.indither = true;
Bitmapoptinos.inpreferredconfig = Bitmap.Config.ARGB_8888;
InputStream = Activity.getcontentresolver (). Openinputstream (URI);

Bitmap Bitmap = Bitmapfactory.decodestream (InputStream, NULL, Bitmapoptinos);
Inputstream.close ();

Return Compressimage (bitmap);
}

/**
* Quality compression method
*
* @param bitmap
* @return
*/
public static Bitmap Compressimage (Bitmap Bitmap) {
Bytearrayoutputstream Bytearrayoutputstream = new Bytearrayoutputstream ();
Bitmap.compress (Bitmap.CompressFormat.JPEG, Bytearrayoutputstream);
int options = 100;
while (Bytearrayoutputstream.tobytearray (). length/1024 > 100) {
Bytearrayoutputstream.reset ();
First parameter: Picture format, second parameter: Picture quality, 100 is highest, 0 is the worst, third parameter: Save the stream of compressed data
Bitmap.compress (Bitmap.CompressFormat.JPEG, Options, Bytearrayoutputstream);
Options-= 10;
}
Bytearrayinputstream Bytearrayinputstream = new Bytearrayinputstream (Bytearrayoutputstream.tobytearray ());
Bitmap bitmapImage = Bitmapfactory.decodestream (bytearrayinputstream, NULL, NULL);
return bitmapImage;
}
}

Androidmainfest.xml:
<?xml version= "1.0" encoding= "Utf-8"?>
<manifest package= "Com.sctu.edu.test"
Xmlns:android= "Http://schemas.android.com/apk/res/android" >
<uses-feature
Android:name= "Android.hardware.camera"
Android:required= "true"
/>

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name= "Android.permission.CAMERA"/>
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name= "Com.miui.whetstone.permission.ACCESS_PROVIDER"/>
<uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:name= "Android.hardware.camera.autofocus"/>

<application
Android:allowbackup= "true"
android:icon= "@mipmap/ic_launcher"
Android:label= "@string/app_name"
Android:supportsrtl= "true"
Android:theme= "@style/apptheme" >
<activity android:name= ". Mainactivity ">
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>

<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

</manifest>

Activity_main.xml:
<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout
Xmlns:android= "Http://schemas.android.com/apk/res/android"
Xmlns:tools= "Http://schemas.android.com/tools"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
Android:background= "#fff"
android:orientation= "Vertical"
tools:context= "Com.sctu.edu.test.MainActivity" >

<button
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Looking for pictures from the gallery"
Android:id= "@+id/gallery"
android:onclick= "Gallery"
Android:background= "#ccc"
Android:textsize= "20SP"
Android:padding= "10DP"
android:layout_marginleft= "30DP"
android:layout_margintop= "40DP"
/>

<button
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Photo Capture"
Android:id= "@+id/camera"
android:onclick= "Camera"
Android:background= "#ccc"
Android:textsize= "20SP"
Android:padding= "10DP"
android:layout_marginleft= "30DP"
android:layout_margintop= "40DP"
/>

<imageview
Android:layout_width= "300DP"
android:layout_height= "300DP"
Android:id= "@+id/imageview"
Android:scaletype= "Fitxy"
android:background= "@mipmap/ic_launcher"
android:layout_margintop= "40DP"
android:layout_marginleft= "30DP"
/>

</LinearLayout>





Some people may ask, how to click on the photo on the Android6.0 to flash back, that is because I set the maximum version of the SDK is greater than 23, and I have not yet to deal with the runtime permissions, perhaps I will deal with this issue in the next blog post. Thank you for browsing, hope to help you!

Android get local album pictures, take photos to get pictures

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.