需求:从本地相册找图片,或通过调用系统相机拍照得到图片。

容易出错的地方:

1,当我们指定了照片的uri路径,我们就不能通过data.getData();来获取uri,而应该直接拿到uri(用全局变量或者其他方式)然后设置给imageView

imageView.setImageURI(uri);

2,我发现手机前置摄像头拍出来的照片只有几百KB,直接用imageView.setImageURI(uri);没有很大问题,但是后置摄像头拍出来的照片比较大,这个时候使用imageView.setImageURI(uri);就容易出现 out of memory(oom)错误,我们需要先把URI转换为Bitmap,再压缩bitmap,然后通过imageView.setImageBitmap(bitmap);来显示图片。

3,将照片存放到SD卡中后,照片不能立即出现在系统相册中,因此我们需要发送广播去提醒相册更新照片。

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转换为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,而我现在还没对运行时权限做处理,也许我会在下一篇博客里处理这个问题。谢谢浏览,希望对你有帮助!

Android获取本地相册图片、拍照获取图片的更多相关文章

  1. Android 从本地图库或拍照后裁剪图片并设置头像

    在QQ和微信等应用都会有设置头像,一般都是从本地图库选取或相机拍照,然后再截图自己喜欢的部分,然后设置.最后一步把截取好的图片再保存到本地,来保存头像.为了大家使用方便,我把自己完整的代码贴出来,大家 ...

  2. Android调用系统相册和拍照的Demo

    最近我在群里看到有好几个人在交流说现在网上的一些Android调用系统相册和拍照的demo都有bug,有问题,没有一个完整的.确实是,我记得一个月前,我一同学也遇到了这样的问题,在低版本的系统中没问题 ...

  3. android 开启本地相册选择图片并返回显示

    .java package com.jerry.crop; import java.io.File; import android.app.Activity; import android.conte ...

  4. Xamarin.Android 调用本地相册

    调用本地相册选中照片在ImageView上显示 代码: using System; using System.Collections.Generic; using System.Linq; using ...

  5. ionic + cordova 使用 cordova-gallery-api 获取本地相册所有图片

    cordova-gallery-api 插件定义一个全局galleryapi对象,提供查询图库相册的方法 安装 cordova-gallery-api: cordova plugin add http ...

  6. IOS 获取系统相册和拍照使用HXPhotoPicker 返回页面时页面上移被nav遮住问题

    解决: - (void)viewWillAppear:(BOOL)animated{    [super viewWillAppear:animated]; self.automaticallyAdj ...

  7. Android选择系统相册或拍照上传

    PhotoUtils.rar

  8. 转载:Android调用相册、拍照实现缩放、切割图片

    好几天没有写博客了,感觉都有点懈怠了.笔者参加了大学生第二届软件设计大赛,这几天 一直在弄大赛的事情,没有花些时间来整理博客.好在经过一些时日比赛的东西也弄得差不多了, 接下来就是将这段时间学习里面有 ...

  9. C#获取网页的HTML码、下载网站图片、获取IP地址

    1.根据URL请求获取页面HTML代码 /// <summary> /// 获取网页的HTML码 /// </summary> /// <param name=" ...

随机推荐

  1. Centos7.2——自定义系统服务

    前言 顾明思议,自己创建系统服务,在上一篇博文中写道了,这里就详细写下~ 步骤 我是一段美丽的用户分割的废话~ 进入到系统服务目录 ··· cd /lib/systemd/system ··· 创建服 ...

  2. java停止线程

    本文将介绍jdk提供的api中停止线程的用法. 停止一个线程意味着在一个线程执行完任务之前放弃当前的操作,停止一个线程可以使用Thread.stop()方法,但是做好不要使用它,它是后继jdk版本中废 ...

  3. c语言中为什么左移不分符号数无符号数,而右移分呢??

    因为在C语言标准中,只规定了无符号数的移位操作是采用逻辑移位(即左移.右移都是使用的逻辑左移和逻辑右移).而对于有符号数,其左移操作还是逻辑左移,但右移操作是采用逻辑右移还是算术右移就取决于机器了!( ...

  4. Vue安装及插件Vue Devtools

    vue安装: # 最新稳定版 $ npm install vue # 全局安装 vue-cli $ npm install --global vue-cli # 创建一个基于 webpack 模板的新 ...

  5. 2018.8.10Yukimai模拟Day1

    这的确是最惨的一次模拟了……不会再惨了(10pts除非爆零orz) 总结一下吧…… T1 .章鱼 众所周知,雪舞喵有许多猫.由于最近的天气十分炎热,雪舞城的大魔法师雪月月根本不想出门,只想宅在家里打隔 ...

  6. unity anim(转)

    Unity4的Mecanim动画很早以前就有体验过,迟迟没有加到项目中有两个原因,今天写这篇博客来记录我在做的过程中遇到的一些问题. 1.以前的代码代码量比较多,修改起来动的地方太多了. 2.使用Me ...

  7. Spring注解的(List&Map)特殊注入功能

    一.先看一个示例演示:spring注解的一个特殊的注入功能. 首先,是定义一个接口,3个实现类. public interface GreetService { public String sayHe ...

  8. ASP.NET Core:Pages

    ylbtech-ASP.NET Core:Pages 1.返回顶部 1._Layout.cshtm <!DOCTYPE html> <html> <head> &l ...

  9. 【旧文章搬运】改PEB中的映像路径可以这样~

    原文发表于百度空间,2008-7-26========================================================================== 用常用的几个 ...

  10. liteos内存(三)

    1. 概述 1.1 基本概念 内存管理模块管理系统的内存资源,它是操作系统的核心模块之一.主要包括内存的初始化.分配以及释放. 在系统运行过程中,内存管理模块通过对内存的申请/释放操作,来管理用户和O ...