Android獲取本地相冊圖片、拍照獲取圖片

需求:從本地相冊找圖片,或經過調用系統相機拍照獲得圖片。java

容易出錯的地方:android

1,當咱們指定了照片的uri路徑,咱們就不能經過data.getData();來獲取uri,而應該直接拿到uri(用全局變量或者其餘方式)而後設置給imageView緩存

imageView.setImageURI(uri);app

2,我發現手機前置攝像頭拍出來的照片只有幾百KB,直接用imageView.setImageURI(uri);沒有很大問題,可是後置攝像頭拍出來的照片比較大,這個時候使用imageView.setImageURI(uri);就容易出現 out of memory(oom)錯誤,咱們須要先把URI轉換爲Bitmap,再壓縮bitmap,而後經過imageView.setImageBitmap(bitmap);來顯示圖片。ide

3,將照片存放到SD卡中後,照片不能當即出如今系統相冊中,所以咱們須要發送廣播去提醒相冊更新照片。ui

4,這裏用到了sharepreference,要注意用完以後移除緩存。this

代碼:spa

MainActivity:.net

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不推薦使用全局變量,我在這裏使用了sharePreference
sharePreference = SharePreference.getInstance(this);
imageView = (ImageView) findViewById(R.id.imageView);
}

//從相冊取圖片
public void gallery(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PHOTO_FROM_GALLERY);
}

//拍照取圖片
public void camera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

uriForCamera = Uri.fromFile(createImageStoragePath());
sharePreference.setCache("uri", String.valueOf(uriForCamera));

/**
* 指定了uri路徑,startActivityForResult不返回intent,
* 因此在onActivityResult()中不能經過data.getData()獲取到uri;
*/
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);
//第一層switch
switch (requestCode) {
case PHOTO_FROM_GALLERY:
//第二層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 {
//把URI轉換爲Bitmap,並將bitmap壓縮,防止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;
}
}

/**
* 設置相片存放路徑,先將照片存放到SD卡中,再操做
*
* @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;
}
}

/**
* 將照片插入系統相冊,提醒相冊更新
*
* @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, "", "");
}

/**
* 判斷SD卡是否可用
*
* @return
*/
private boolean hasSdcard() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}

/**
* 移除緩存
*
* @param cache
*/
private void removeCache(String cache) {
if (sharePreference.ifHaveShare(cache)) {
sharePreference.removeOneCache(cache);
} else {
Log.e("this cache", "is 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 {

/**
* 經過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表示不縮放
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);
}

/**
* 質量壓縮方法
*
* @param bitmap
* @return
*/
public static Bitmap compressImage(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
int options = 100;
while (byteArrayOutputStream.toByteArray().length / 1024 > 100) {
byteArrayOutputStream.reset();
//第一個參數 :圖片格式 ,第二個參數: 圖片質量,100爲最高,0爲最差  ,第三個參數:保存壓縮後的數據的流
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="從圖庫找圖片"
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="拍照獲取圖片"
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>



效果圖:

        

 

或許有人會問,在Android6.0上面怎麼點擊拍照就出現閃退,那是由於我設置的最高SDK版本大於23,而我如今還沒對運行時權限作處理,也許我會在下一篇博客裏處理這個問題。謝謝瀏覽,但願對你有幫助!code

相關文章
相關標籤/搜索