Android 之 打开系统摄像头拍照 打开系统相册,并展示

1,清单文件 AndroidManifest.xml

```

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

<!--文件读取权限-->

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

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

<!--相机权限-->

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

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

<uses-feature android:name="android.hardware.camera.autofocus" />

<application ...>

...

<provider

android:name="androidx.core.content.FileProvider"

android:authorities="com.example.camera.fileprovider"

android:grantUriPermissions="true">

<meta-data

android:name="android.support.FILE_PROVIDER_PATHS"

android:resource="@xml/my_image" />

</provider>

</application>

```

2,配置文件 my_image.xml

```

<?xml version="1.0" encoding="utf-8"?>

<paths xmlns:android="" target="_blank">http://schemas.android.com/apk/res/android">

<external-path

name="my_image"

path="/" />

</paths>

```

3,布局

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context="com.sjl.nfc.MainActivity">

<ImageView

android:id="@+id/main_img01"

android:layout_width="200dp"

android:layout_height="200dp"

android:layout_gravity="center_horizontal"

android:src="@drawable/img_mine06" />

<Button

android:id="@+id/main_btn01"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_horizontal"

android:text="打开相机" />

<Button

android:id="@+id/main_btn02"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_horizontal"

android:text="打开相册" />

</LinearLayout>

4,主要代码 java

package com.sjl.nfc;

import android.annotation.TargetApi;

import android.app.Activity;

import android.content.ContentUris;

import android.content.Intent;

import android.database.Cursor;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.drawable.BitmapDrawable;

import android.net.Uri;

import android.os.Bundle;

import android.provider.DocumentsContract;

import android.provider.MediaStore;

import android.util.Base64;

import android.util.Log;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.Toast;

import androidx.annotation.Nullable;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.content.FileProvider;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

/**

* 项目模板

*/

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

private ImageView main_img01;

private Uri imageUri;

@Override

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main_activity);

main_img01 = findViewById(R.id.main_img01);

Button main_btn01 = findViewById(R.id.main_btn01); // 打开相机

Button main_btn02 = findViewById(R.id.main_btn02); // 打开相册

main_btn01.setOnClickListener(v -> {

// 打开相机

File outputImage = new File(getExternalCacheDir(), "shenhuiran_" + System.currentTimeMillis() + ".jpg"); // 名称(“shenhuiran_”+系统当前时间Millis()

if (outputImage.exists()) outputImage.delete();

try {

outputImage.createNewFile();

} catch (IOException e) {

e.printStackTrace();

}

imageUri = FileProvider.getUriForFile(this, "com.example.camera.fileprovider", outputImage);

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

startActivityForResult(intent, TAKE_PHOTO);

});

main_btn02.setOnClickListener(v -> {

// 打开相册

// 在Activity Action里面有一个“ACTION_GET_CONTENT”字符串常量,

// 该常量让用户选择特定类型的数据,并返回该数据的URI.我们利用该常量,

// 然后设置类型为“image/*”,就可获得Android手机内的所有image。*/

Intent intent = new Intent("android.intent.action.GET_CONTENT");

intent.setType("image/*"); // 开启Pictures画面Type设定为image

// 打开相册

startActivityForResult(intent, CHOOSE_PHOTO);

});

}

/**

* 获取活动或片段的位图和图像路径onActivityResult

*

* @param requestCode

* @param resultCode

* @param data

*/

public static final int TAKE_PHOTO = 1;

public static final int CROP_PHOTO = 2;

public static final int CHOOSE_PHOTO = 3;

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

switch (requestCode) {

case TAKE_PHOTO:

if (resultCode == Activity.RESULT_OK) {

try {

Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));

main_img01.setImageBitmap(bitmap); // 展示刚拍过的照片

getImgBase64(main_img01); // 直接把 imageview 取出图片转换为base64格式

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

break;

case CROP_PHOTO:

if (resultCode == RESULT_OK) {

try {

Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));

// 显示裁剪后的图片

main_img01.setImageBitmap(bitmap);

} catch (FileNotFoundException ex) {

ex.printStackTrace();

}

}

break;

case CHOOSE_PHOTO:

if (resultCode == RESULT_OK) {

handleImage(data);

}

break;

default:

break;

}

}

// 只在Android4.4及以上版本使用

@TargetApi(19)

private void handleImage(Intent data) {

String imagePath = null;

Uri uri = data.getData();

if (DocumentsContract.isDocumentUri(this, uri)) {

// 通过document id来处理

String docId = DocumentsContract.getDocumentId(uri);

if ("com.android.providers.media.documents".equals(uri.getAuthority())) {

// 解析出数字id

String id = docId.split(":")[1];

String selection = MediaStore.Images.Media._ID + "=" + id;

imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {

Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));

imagePath = getImagePath(contentUri, null);

}

} else if ("content".equals(uri.getScheme())) {

// 如果不是document类型的Uri,则使用普通方式处理

imagePath = getImagePath(uri, null);

}

// 根据图片路径显示图片

displayImage(imagePath);

}

private String getImagePath(Uri uri, String selection) {

String path = null;

// 通过Uri和selection来获取真实图片路径

Cursor cursor = getContentResolver().query(uri, null, selection, null, null);

if (cursor != null) {

if (cursor.moveToFirst()) {

path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));

}

cursor.close();

}

return path;

}

private void displayImage(String imagePath) {

if (imagePath != null) {

Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

main_img01.setImageBitmap(bitmap);

} else {

Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();

}

}

/**

* imageview取出图片转换为base64格式

*

* @param imageView

* @return

*/

private String takeimage;

public String getImgBase64(ImageView imageView) {

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();

Bitmap bitmap = drawable.getBitmap();

ByteArrayOutputStream bos = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);

byte[] bb = bos.toByteArray();

takeimage = Base64.encodeToString(bb, Base64.NO_WRAP);

Log.d("111111 TakeActivity >>", "打印base64>>:" + takeimage);

// takeTv.setText("打印base64>>:" + image);

// jsJson.put("photographAdditionBase64", "data:image/png;base64," + takeimageview); // 图片上传,上传

return takeimage;

}

}

Android 之 打开相机 打开相册相关推荐

  1. android调用相机与相册的方法,Android打开相机和相册实例代码

    本文实例为大家分享了Android打开相机和相册具体代码,供大家参考,具体内容如下 打开相机 /** * 选择相机 */ private void showCamera() { // 跳转到系统照相机 ...

  2. Vue+Element-UI 上传图片,打开相机,相册

    Vue+Element-UI 上传图片,打开相机,相册 Element-UI中提供的Upload组件,是用来上传文件用的,并没有单独的纯用来上传图片的组件,所以,在部分浏览器(手机)中,打开后会发现是 ...

  3. 关于手机横屏打开相机或者相册闪退解决方案

    今天遇到一个需求就是在手机横屏的时候要打开相册相机,但是在打开的手就报错,经过一上午的查资料,看文档,知道了问题所在,原来UIImagePickerController 只支持竖屏 解决思路 1,让U ...

  4. Android调用系统相机和相册(更换微信头像)

    最近做了调用系统相机和相册,在其他博客中看到还有对图像进行剪切,大家都知道,我们在玩微信的时候,头像更换是方形图片,接下来我们就对这种情况具体进行描述: 必要的权限: <uses-permiss ...

  5. android 打开相册的权限,Android 启动系统相机,相册,裁剪图片及6.0权限管理

    在日常开发中,我们经常需要用到上传图片的 功能,这个时候通常有两种做法,第一种,从相机获取,第二种,从相册获取.今天这篇博客主要讲解利用系统的Intent怎样获取? 主要内容如下 怎样通过相机获取我们 ...

  6. UIPickerViewController 打开相机 图库 相册

    iOS 获取图片有三种方法: 1. 直接调用摄像头拍照 2. 从相册中选择 3. 从图库中选择 self.picker = [[UIImagePickerController alloc] init] ...

  7. Android 启动系统相机,相册,裁剪图片及6.0权限管理

    在日常开发中,我们经常需要用到上传图片的 功能,这个时候通常有两种做法,第一种,从相机获取,第二种,从相册获取.今天这篇博客主要讲解利用系统的Intent怎样获取? 主要内容如下 - 怎样通过相机获取 ...

  8. android调用相机与相册的方法,手把手教你:android调用系统相机、相册功能,适配6.0权限获取以及7.0之后获取URI(兼容多版本)...

    Android中调用系统相机来拍摄照片的代码,以下:html 一.首先设置Uri获取判断以及相机请求Codejava public final int TYPE_TAKE_PHOTO = 1;//Ur ...

  9. Android中使用相机和相册获取照片,模仿朋友圈发说说

    话不多说,直接上图,如图: 这个功能相信很多人都会用到,下面来一步一步的设置这个功能. 1:首先布局我们的主界面,这里我使用activity_edit_diary.xml文件来当布局文件: 文件内容如 ...

最新文章

  1. python项目面试_Python面试中最常见的25个问题-结束
  2. python buildin 中的一些类中为什么方法的内容都是pass?
  3. 58同城沈剑:好的架构源于不停地衍变,而非设计
  4. 深度解析Google Java 编程风格指南
  5. [原]第一次遭遇Oracle的Bug,纪念一下 |ORA-00600 kmgs_pre_process_request_6|
  6. 前端学习(2688):重读vue电商网站9之el-menu 默认会有一个 border-right
  7. day16-Dom提交表单以及其他
  8. VSS 请求程序和 SharePoint 2013
  9. 数据科学 IPython 笔记本 8.5 简单的散点图
  10. Table_Vue table 表格中显示内容过长显示省略号_并且显示提示---SpringCloud Alibaba_若依微服务框架改造_前端ElementUI---工作笔记010
  11. PXE无人值守系统安装配置简要说明
  12. 对于最小割的进一步理解
  13. pytorch之学习率变化策略之MultiplicativeLR
  14. centos通过yum的方式快速安装jdk1.8
  15. TCP/IP协议学习(五) 基于C# Socket的C/S模型
  16. 【Java面试题】9 abstract class和interface有什么区别?
  17. 自学-Linux-老男孩Linux77期-day3
  18. 数学建模数据驱动之统计学预备知识
  19. “3G域名”遭恶炒 用友移动代理被指画饼圈钱
  20. Alkyne-PEG-MAL 炔烃PEG马来酰亚胺

热门文章

  1. 在C语言中使用二分法算法思想解决猜商品价格问题
  2. Linux命令之查看行号
  3. 告别 .com网址时代,Opera浏览器实现用Emoji符号打开网站
  4. 判断三角形(PTA厦大慕课)
  5. 年终考核 对你的上司,你是如何评价的
  6. 高等数学:第三章 微分中值定理与导数的应用(8)曲率
  7. UNIX时间戳的应用-JAVA
  8. Fiddler抓包6-打断点(bpu)
  9. 何为非侵入式负荷分解
  10. 昆仑万维:如涵在纳斯达克挂牌 公司持有其3.91%股权