Android 实例解说加入本地图片和调用系统拍照图片
在项目的开发过程我们离不开图片。而有时候须要调用本地的图片,有时候须要调用拍照图片。同一时候实现拍照的方法有两种,一种是调用系统拍照功能。还有一种是自己定义拍照功能。
而本博文眼下仅仅解说第一种方法,另外一种方法后期在加以解说。
加入本地图片和调用系统拍照图片主要是通过调用acitivity跳转startActivityForResult(Intent intent, int requestCode)方法和activity返回结果onActivityResult(int
requestCode, int resultCode, Intent data)方法来实现的。详细实现代码例如以下:
一.加入本地图片
1.
- Intent intent = new Intent();
- /* 开启Pictures画面Type设定为image */
- intent.setType(IMAGE_TYPE);
- /* 使用Intent.ACTION_GET_CONTENT这个Action */
- intent.setAction(Intent.ACTION_GET_CONTENT);
- /* 取得相片后返回本画面 */
- startActivityForResult(intent, LOCAL_IMAGE_CODE);</span>
2.
- Uri uri = data.getData();
- url = uri.toString().substring(uri.toString().indexOf("///") + 2);
- if (url.contains(".jpg") && url.contains(".png")) {
- Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
- return;
- }
- bitmap = HelpUtil.getBitmapByUrl(url);
二.调用系统拍照图片
1.
- String fileName = "IMG_" + curFormatDateStr + ".png";
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(rootUrl, fileName)));
- intent.putExtra("fileName", fileName);
- startActivityForResult(intent, CAMERA_IMAGE_CODE);
2.
- url = rootUrl + "/" + "IMG_" + curFormatDateStr + ".png";
- bitmap = HelpUtil.getBitmapByUrl(url);
- showImageIv.setImageBitmap(HelpUtil.createRotateBitmap(bitmap));
注意:因为拍照所得图片放在ImageView中自己主动逆时针旋转了90度,当显示的实现须要顺时针旋转90度,达到正常显示水平。方法例如以下
- /**
- * bitmap旋转90度
- *
- * @param bitmap
- * @return
- */
- public static Bitmap createRotateBitmap(Bitmap bitmap) {
- if (bitmap != null) {
- Matrix m = new Matrix();
- try {
- m.setRotate(90, bitmap.getWidth() / 2, bitmap.getHeight() / 2);// 90就是我们须要选择的90度
- Bitmap bmp2 = Bitmap.createBitmap(bitmap, 0, 0,
- bitmap.getWidth(), bitmap.getHeight(), m, true);
- bitmap.recycle();
- bitmap = bmp2;
- } catch (Exception ex) {
- System.out.print("创建图片失败!" + ex);
- }
- }
- return bitmap;
- }
三.实例给出整个效果的具体代码
1.效果图
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTEyM2RlbWk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
2.布局文件activity_main.xml
- <RelativeLayout 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" >
- <LinearLayout
- android:id="@+id/id_insert_btns_ll"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:orientation="horizontal" >
- <Button
- android:id="@+id/id_local_img_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="插入本地图片" />
- <Button
- android:id="@+id/id_camera_img_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="插入拍照图片" />
- </LinearLayout>
- <TextView
- android:id="@+id/id_show_url_tv"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:layout_alignParentBottom="true"
- android:textColor="#FF0000"
- android:text="显示图片路径" />
- <ImageView
- android:id="@+id/id_image_iv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@id/id_insert_btns_ll"
- android:layout_above="@id/id_show_url_tv"
- android:layout_centerHorizontal="true"
- />
- </RelativeLayout>
3.主类文件MainActivity.java
- package com.example.insertimagedemo;
- import java.io.File;
- import java.util.Calendar;
- import android.app.Activity;
- import android.content.Intent;
- import android.graphics.Bitmap;
- import android.net.Uri;
- import android.os.Bundle;
- import android.os.Environment;
- import android.provider.MediaStore;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity implements OnClickListener {
- private static final int LOCAL_IMAGE_CODE = 1;
- private static final int CAMERA_IMAGE_CODE = 2;
- private static final String IMAGE_TYPE = "image/*";
- private String rootUrl = null;
- private String curFormatDateStr = null;
- private Button localImgBtn, cameraImgBtn;
- private TextView showUrlTv;
- private ImageView showImageIv;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- findById();
- initData();
- }
- /**
- * 初始化view
- */
- private void findById() {
- localImgBtn = (Button) this.findViewById(R.id.id_local_img_btn);
- cameraImgBtn = (Button) this.findViewById(R.id.id_camera_img_btn);
- showUrlTv = (TextView) this.findViewById(R.id.id_show_url_tv);
- showImageIv = (ImageView) this.findViewById(R.id.id_image_iv);
- localImgBtn.setOnClickListener(this);
- cameraImgBtn.setOnClickListener(this);
- }
- /**
- * 初始化相关data
- */
- private void initData() {
- rootUrl = Environment.getExternalStorageDirectory().getPath();
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.id_local_img_btn:
- processLocal();
- break;
- case R.id.id_camera_img_btn:
- processCamera();
- break;
- }
- }
- /**
- * 处理本地图片btn事件
- */
- private void processLocal() {
- Intent intent = new Intent();
- /* 开启Pictures画面Type设定为image */
- intent.setType(IMAGE_TYPE);
- /* 使用Intent.ACTION_GET_CONTENT这个Action */
- intent.setAction(Intent.ACTION_GET_CONTENT);
- /* 取得相片后返回本画面 */
- startActivityForResult(intent, LOCAL_IMAGE_CODE);
- }
- /**
- * 处理camera图片btn事件
- */
- private void processCamera() {
- curFormatDateStr = HelpUtil.getDateFormatString(Calendar.getInstance()
- .getTime());
- String fileName = "IMG_" + curFormatDateStr + ".png";
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- intent.putExtra(MediaStore.EXTRA_OUTPUT,
- Uri.fromFile(new File(rootUrl, fileName)));
- intent.putExtra("fileName", fileName);
- startActivityForResult(intent, CAMERA_IMAGE_CODE);
- }
- /**
- * 处理Activity跳转后返回事件
- */
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (resultCode == RESULT_OK) {
- String url = "";
- Bitmap bitmap = null;
- if (requestCode == LOCAL_IMAGE_CODE) {
- Uri uri = data.getData();
- url = uri.toString().substring(
- uri.toString().indexOf("///") + 2);
- Log.e("uri", uri.toString());
- if (url.contains(".jpg") && url.contains(".png")) {
- Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
- return;
- }
- bitmap = HelpUtil.getBitmapByUrl(url);
- showImageIv.setImageBitmap(HelpUtil.getBitmapByUrl(url));
- /**
- * 获取bitmap还有一种方法
- *
- * ContentResolver cr = this.getContentResolver(); bitmap =
- * HelpUtil.getBitmapByUri(uri, cr);
- */
- } else if (requestCode == CAMERA_IMAGE_CODE) {
- url = rootUrl + "/" + "IMG_" + curFormatDateStr + ".png";
- bitmap = HelpUtil.getBitmapByUrl(url);
- showImageIv.setImageBitmap(HelpUtil.createRotateBitmap(bitmap));
- /**
- * 获取bitmap还有一种方法
- *
- * File picture = new File(url);
- * Uri uri = Uri.fromFile(picture);
- * ContentResolver cr = this.getContentResolver();
- * bitmap = HelpUtil.getBitmapByUri(uri, cr);
- */
- }
- showUrlTv.setText(url);
- } else {
- Toast.makeText(this, "没有加入图片", Toast.LENGTH_SHORT).show();
- }
- }
- }
4.帮助类文件HelpUtil.java
- package com.example.insertimagedemo;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import android.annotation.SuppressLint;
- import android.content.ContentResolver;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Matrix;
- import android.net.Uri;
- public class HelpUtil {
- /**
- * 依据图片路径获取本地图片的Bitmap
- *
- * @param url
- * @return
- */
- public static Bitmap getBitmapByUrl(String url) {
- FileInputStream fis = null;
- Bitmap bitmap = null;
- try {
- fis = new FileInputStream(url);
- bitmap = BitmapFactory.decodeStream(fis);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- bitmap = null;
- } finally {
- if (fis != null) {
- try {
- fis.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- fis = null;
- }
- }
- return bitmap;
- }
- /**
- * bitmap旋转90度
- *
- * @param bitmap
- * @return
- */
- public static Bitmap createRotateBitmap(Bitmap bitmap) {
- if (bitmap != null) {
- Matrix m = new Matrix();
- try {
- m.setRotate(90, bitmap.getWidth() / 2, bitmap.getHeight() / 2);// 90就是我们须要选择的90度
- Bitmap bmp2 = Bitmap.createBitmap(bitmap, 0, 0,
- bitmap.getWidth(), bitmap.getHeight(), m, true);
- bitmap.recycle();
- bitmap = bmp2;
- } catch (Exception ex) {
- System.out.print("创建图片失败。" + ex);
- }
- }
- return bitmap;
- }
- public static Bitmap getBitmapByUri(Uri uri,ContentResolver cr){
- Bitmap bitmap = null;
- try {
- bitmap = BitmapFactory.decodeStream(cr
- .openInputStream(uri));
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- bitmap = null;
- }
- return bitmap;
- }
- /**
- * 获取格式化日期字符串
- * @param date
- * @return
- */
- @SuppressLint("SimpleDateFormat")
- public static String getDateFormatString(Date date) {
- if (date == null)
- date = new Date();
- String formatStr = new String();
- SimpleDateFormat matter = new SimpleDateFormat("yyyyMMdd_HHmmss");
- formatStr = matter.format(date);
- return formatStr;
- }
- }
曾经就是本博文全部内容,谢谢品读。
Android 实例解说加入本地图片和调用系统拍照图片的更多相关文章
- Java乔晓松-android中调用系统拍照功能并显示拍照的图片
android中调用系统拍照功能并显示拍照的图片 如果你是拍照完,利用onActivityResult获取data数据,把data数据转换成Bitmap数据,这样获取到的图片,是拍照的照片的缩略图 代 ...
- Android上传图片之调用系统拍照和从相冊选择图片
Android上传图片之调用系统拍照和从相冊选择图片 本篇文章已授权微信公众号 guolin_blog (郭霖)独家公布 前言: 万丈高楼平底起,万事起于微末.不知不觉距离上篇博文已近四个月,2015 ...
- Android调用系统拍照裁剪和选图功能
最近项目中用到修改用户头像的功能,基本上都是模板代码,现在简单记录一下. 调用系统拍照 private fun openCamera() { //调用相机拍照 // 创建File对象,用于存储拍照后的 ...
- 摄像头(3)调用系统拍照activity来拍照
import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager ...
- 摄像头(2)调用系统拍照activity来录像
import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager ...
- HTML5: 实现调用系统拍照或者选择照片并预览
ylbtech-HTML5: 实现调用系统拍照或者选择照片并预览 1.返回顶部 1. <!DOCTYPE html> <html> <head> <meta ...
- android 7.0以上共享文件(解决调用系统照相和图片剪切出现的FileUriExposedException崩溃问题)
在android7.0开始试共享“file://”URI 将会导致引发 FileUriExposedException. 如果应用需要与其他应用共享私有文件,则应该使用 FileProvider, F ...
- 关于android中调用系统拍照,返回图片是旋转90度
转载博客:http://blog.csdn.net/walker02/article/details/8211628 项目开发中遇到的一个问题,对于三星手机在做手机照片选择时出现图片显示不正常,研究后 ...
- c# 调用系统默认图片浏览器打开图片
private void OpenImage(string fileName) { try { Process.Start(fileName); } catch (Exception ex) { // ...
随机推荐
- 【LeetCode】Two Sum(两数之和)
这道题是LeetCode里的第1道题. 题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会 ...
- NYOJ 814 又见拦截导弹
又见拦截导弹 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 大家对拦截导弹那个题目应该比较熟悉了,我再叙述一下题意:某国为了防御敌国的导弹袭击,新研制出来一种导弹拦 ...
- 九度oj 题目1017:还是畅通工程
题目描述: 某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离.省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可 ...
- JavaWeb基础(HTML)
代码改变世界 HTML HTML是指超本标记语言,它不是编程语言,而是一种标记语言.标记语言是一套标记标签,HTML使用标记标签来描述网页,用以定义如何在页面上展示信息. 1.HTML标签 HTML标 ...
- Python之注册表增删改查(干货)
在Windows平台下,对注册表的增删改查的需求比较多,微软提供了很多用于访问,修改注册表等的API,我们可以使用诸如bat,或者C++等各种方式去访问修改注册表.无所不能的python下如何完成这些 ...
- 【Luogu】P1602Sramoc问题(堆)
题目链接 很巧妙的想法.一开始将1~k-1加入堆中,然后每次从堆里取出一个最小的,判断是不是答案,如果不是,那么就枚举新数的末一位加上. 代码如下 #include<cstdio> #in ...
- 2016 ACM-ICPC China Finals #F Mr. Panda and Fantastic Beasts
题目链接$\newcommand{\LCP}{\mathrm{LCP}}\newcommand{\suf}{\mathrm{suf}}$ 题意 给定 $n$ 个字符串 $s_1, s_2, \dots ...
- 【树状数组区间修改单点查询】HDU 4031 Attack
http://acm.hdu.edu.cn/showproblem.php?pid=4031 [题意] 有一个长为n的长城,进行q次操作,d为防护罩的冷却时间,Attack表示区间a-b的墙将在1秒后 ...
- 【扫描线或树状数组】CSU 1335 高桥和低桥
http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1335 [题意] 给定n座桥的高度,给定m次洪水每次的涨水水位ai和退水水位bi 询问有多少座桥 ...
- 【2018.10.15】WZJ笔记(数论)
1. 证明:对于任意质数$p\gt 3$,$p^2-1$能被$24$整除. 证:平方差公式,$p^2-1 = (p-1)(p+1)$. 再把$24$分解质因数$2^3*3$. 三个相邻的自然数中至少有 ...