Android獲取本地相冊圖片和拍照獲取圖片的實現(xiàn)方法
需求:從本地相冊找圖片,或通過調(diào)用系統(tǒng)相機拍照得到圖片。
容易出錯的地方:
1、當我們指定了照片的uri路徑,我們就不能通過data.getData();來獲取uri,而應該直接拿到uri(用全局變量或者其他方式)然后設(shè)置給imageView
imageView.setImageURI(uri);
2、我發(fā)現(xiàn)手機前置攝像頭拍出來的照片只有幾百KB,直接用imageView.setImageURI(uri);沒有很大問題,但是后置攝像頭拍出來的照片比較大,這個時候使用imageView.setImageURI(uri);就容易出現(xiàn) out of memory(oom)錯誤,我們需要先把URI轉(zhuǎn)換為Bitmap,再壓縮bitmap,然后通過imageView.setImageBitmap(bitmap);來顯示圖片。
3、將照片存放到SD卡中后,照片不能立即出現(xiàn)在系統(tǒng)相冊中,因此我們需要發(fā)送廣播去提醒相冊更新照片。
4、這里用到了sharepreference,要注意用完之后移除緩存。
代碼:
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不推薦使用全局變量,我在這里使用了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轉(zhuǎn)換為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;
}
}
/**
* 設(shè)置相片存放路徑,先將照片存放到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;
}
}
/**
* 將照片插入系統(tǒng)相冊,提醒相冊更新
*
* @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);
}
/**
* 質(zhì)量壓縮方法
*
* @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();
//第一個參數(shù) :圖片格式 ,第二個參數(shù): 圖片質(zhì)量,100為最高,0為最差 ,第三個參數(shù):保存壓縮后的數(shù)據(jù)的流
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上面怎么點擊拍照就出現(xiàn)閃退,那是因為我設(shè)置的最高SDK版本大于23,而我現(xiàn)在還沒對運行時權(quán)限做處理,也許我會在下一篇博客里處理這個問題。謝謝瀏覽,希望對你有幫助!
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android自定義View實現(xiàn)音頻播放圓形進度條
這篇文章主要為大家詳細介紹了Android自定義View實現(xiàn)音頻播放圓形進度條,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06
Android編程設(shè)置TextView顏色setTextColor用法實例
這篇文章主要介紹了Android編程設(shè)置TextView顏色setTextColor用法,結(jié)合實例形式分析了Android設(shè)置TextView顏色setTextColor、ColorStateList等方法的使用技巧與布局文件的設(shè)置方法,需要的朋友可以參考下2016-01-01
使用androidx BiometricPrompt實現(xiàn)指紋驗證功能
這篇文章主要介紹了使用androidx BiometricPrompt實現(xiàn)指紋驗證功能,對android指紋驗證相關(guān)知識感興趣的朋友跟隨小編一起看看吧2021-07-07
Android?DialogFragment使用之底部彈窗封裝示例
這篇文章主要為大家介紹了Android?DialogFragment使用之底部彈窗封裝示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
Android RecyclerView實現(xiàn)滑動刪除
這篇文章主要為大家詳細介紹了Android RecyclerView實現(xiàn)滑動刪除,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-07-07
Android自定義view利用Xfermode實現(xiàn)動態(tài)文字加載動畫
這篇文章主要介紹了Android自定義view利用Xfermode實現(xiàn)動態(tài)文字加載動畫,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
使用flutter的showModalBottomSheet遇到的坑及解決
這篇文章主要介紹了使用flutter的showModalBottomSheet遇到的坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

