android摄像头拍照代码,Android调用摄像头拍照开发教程
现在很多应用中都会要求用户上传一张图片来作为头像,首先我在这接收使用相机拍照和在相册中选择图片。接下来先上效果图:
接下来看代码:
1、布局文件:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.gyq.cameraalbumtest.MainActivity">
android:id="@+id/btn_take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="take photo"/>
android:id="@+id/choose_from_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="choose from album"/>
android:id="@+id/iv_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
2、MainActivity.java逻辑代码:
package com.gyq.cameraalbumtest;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
public static final int CHOOSE_PHOTO = 2;
private Button mTakePhoto, mChoosePhoto;
private ImageView picture;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTakePhoto = (Button) findViewById(R.id.btn_take_photo);
mChoosePhoto = (Button) findViewById(R.id.choose_from_album);
picture = (ImageView) findViewById(R.id.iv_picture);
mTakePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//创建file对象,用于存储拍照后的图片;
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24) {
imageUri = FileProvider.getUriForFile(MainActivity.this,
"com.gyq.cameraalbumtest.fileprovider", outputImage);
} else {
imageUri = Uri.fromFile(outputImage);
}
//启动相机程序
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
mChoosePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
openAlbum();
}
}
});
}
//打开相册
private void openAlbum() {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
Toast.makeText(this, "you denied the permission", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bm);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= 19) { //4.4及以上的系统使用这个方法处理图片;
handleImageOnKitKat(data);
} else {
handleImageBeforeKitKat(data); //4.4及以下的系统使用这个方法处理图片
}
}
default:
break;
}
}
private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String 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);
picture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
}
}
/**
* 4.4及以上的系统使用这个方法处理图片
*
* @param data
*/
@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
//如果document类型的Uri,则通过document来处理
String docID = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docID.split(":")[1]; //解析出数字格式的id
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/piblic_downloads"), Long.valueOf(docID));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
//如果是content类型的uri,则使用普通方式使用
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
//如果是file类型的uri,直接获取路径即可
imagePath = uri.getPath();
}
displayImage(imagePath);
}
}
3、清单文件:
package="com.gyq.cameraalbumtest">
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
android:authorities="com.gyq.cameraalbumtest.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
android:resource="@xml/file_paths"/>
4、xml文件夹中的文件
OK,完成收工。请继续关注我的博客。谢谢!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
android摄像头拍照代码,Android调用摄像头拍照开发教程相关推荐
- 三星手机拍照旋转问题 调用相机拍照出现横竖屏切换?
三星手机拍照旋转问题 调用相机 拍照出现横竖屏切换? 拍照获取图片时,当应用是竖屏时,在部分手机上,如:三星note3上,图片不能正常显示,会旋转90°. =_= 大概的思路就是拍照后获取图片旋转的角 ...
- linux中cv调用摄像头,ubuntu中opencv调用摄像头
ubuntu中opencv调用摄像头 ubuntu中opencv调用摄像头 文章目录 一.Ubuntu中安装opencv 二.关于Linux如何开启摄像头 1.安装VMvareTools,这个是真的强 ...
- Android Camera相机开发示例、Android 开发板 USB摄像头采集、定期拍照、定时拍照,安卓调用摄像头拍照、Android摄像头预览、监控,USB摄像头开发、摄像头监控代码
我们有个需求,在机器上加个摄像头,定时拍照: 我到网上搜索,发现没有快速上手和简单使用的: 个人感觉,大部分博客写得很乱,或者长篇大论: 而我只想简单实现功能,并不打算学习多少理论: 下面代码是我写来 ...
- android相机拍照代码,Android 调用相机拍照,适配到Android 10
今天写的博客是关于Android调用手机相机拍照并显示图片.这是一个很常用的功能,并且这个功能在Android6.0.7.0.10.0等版本上实现都有所不同,需要对Android各个版本进行兼容适配, ...
- android读取外部图片,Android读取本地图库与调用摄像头拍摄
本文主要介绍如何读取Android本地图库的图片以及调用安卓的摄像头进行拍摄. 一.布局 布局比较简单,MainActviivty的布局文件只有两个按钮,一个是读取图库的,另一个是打开摄像头的,另外R ...
- android加载本地图库,Android读取本地图库与调用摄像头拍摄
本文主要介绍如何读取Android本地图库的图片以及调用安卓的摄像头进行拍摄. 一.布局 布局比较简单,MainActviivty的布局文件只有两个按钮,一个是读取图库的,另一个是打开摄像头的,另外R ...
- android控制手机拍照代码,Android开发之手机拍照功能的实现(源代码分享)
Android系统里调用手机拍照的功能有两种方法一种直接调用手机自带的相机另一种就是使用自己做的拍照应用.比如Camera360 一款于各操作系统都有的的功能强大的手机摄影软件:能拍摄出不同风格,不同 ...
- python开启摄像的代码_python调用摄像头的示例代码
一.打开摄像头 import cv2 import numpy as np def video_demo(): capture = cv2.VideoCapture(0)#0为电脑内置摄像头 whil ...
- jquery 访问手机摄像头_jQuery webcam plugin调用摄像头
简介 原来做项目遇到了调用摄像头功能,php小白遇到这情况立刻就去网上搜索,最后用的 https://www.helloweba.com/vie...,太烂了,作者也没说如何去使用,如果用的是框架开发 ...
最新文章
- jquery拓展插件开发
- 有关函数模板和类模板的说法
- KDDockWidgets源码编译及安装
- ajax乱码解决汇总
- I2C和SPI注定要打一架
- OpenCV3学习(2.3)——图像读取与鼠标截图
- 温故而知新 js 的错误处理机制
- 计算机操作日志文件,教你完全读懂Windows日志文件
- word文档插入尾注,并且设置尾注在参考文献这一章
- 4G模块 EC03-DNC的常用AT指令操作及模块访问内网方法
- 第27月第25天 clang -rewrite-objc main.m
- 2023年社交平台研究报告
- android的反调试方法,Android平台融合多特征的APP反调试方法与流程
- ArcGIS删除字段
- 1. Java POI 读取、写入Excel(包括样式)的工具类Utils
- 腾讯云windows server搭建valheim(英灵神殿)服务器
- 详解java集合框架
- Eckart-Young-Mirsky theorem
- C#海康威视人脸设备-创建人脸信息,并同步到数据库
- 樱花服务器能在运行吗,樱花服务器在运行吗
热门文章
- 活动回顾 |阿里云MVP Tech Show 第九期宁波站— 物联网一站式开发
- openGL es2.0 粒子系统之烟花
- 2022-2028年全球与中国各向异性导电胶行业市场前瞻与投资战略规划分析
- “图书管理系统”数据视图
- php前端语言三套语文卷子,2018高考语文语言文字运用模拟题及答案(3.4)
- 【今日分享】官方实例用python调用OpenAI tahcTPG的APIkey生成智能问答
- 善于计划,善于总结,善于归纳
- html 滑屏 效果,HTML5 web app实现手动页面滑屏效果
- echarts饼图自动显示数据
- Dapr+Net6 服务调用09:集群指标收集-普罗米修斯