在项目的开发过程我们离不开图片。而有时候须要调用本地的图片,有时候须要调用拍照图片。同一时候实现拍照的方法有两种,一种是调用系统拍照功能。还有一种是自己定义拍照功能。

而本博文眼下仅仅解说第一种方法,另外一种方法后期在加以解说。

加入本地图片和调用系统拍照图片主要是通过调用acitivity跳转startActivityForResult(Intent intent, int requestCode)方法和activity返回结果onActivityResult(int
requestCode, int resultCode, Intent data)方法来实现的。详细实现代码例如以下:

一.加入本地图片

1.

  1. Intent intent = new Intent();
  2. /* 开启Pictures画面Type设定为image */
  3. intent.setType(IMAGE_TYPE);
  4. /* 使用Intent.ACTION_GET_CONTENT这个Action */
  5. intent.setAction(Intent.ACTION_GET_CONTENT);
  6. /* 取得相片后返回本画面 */
  7. startActivityForResult(intent, LOCAL_IMAGE_CODE);</span>

2.

  1. Uri uri = data.getData();
  2. url = uri.toString().substring(uri.toString().indexOf("///") + 2);
  3. if (url.contains(".jpg") && url.contains(".png")) {
  4. Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
  5. return;
  6. }
  7. bitmap = HelpUtil.getBitmapByUrl(url);

二.调用系统拍照图片

1.

  1. String fileName = "IMG_" + curFormatDateStr + ".png";
  2. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  3. intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(rootUrl, fileName)));
  4. intent.putExtra("fileName", fileName);
  5. startActivityForResult(intent, CAMERA_IMAGE_CODE);

2.

  1. url = rootUrl + "/" + "IMG_" + curFormatDateStr + ".png";
  2. bitmap = HelpUtil.getBitmapByUrl(url);
  3. showImageIv.setImageBitmap(HelpUtil.createRotateBitmap(bitmap));

注意:因为拍照所得图片放在ImageView中自己主动逆时针旋转了90度,当显示的实现须要顺时针旋转90度,达到正常显示水平。方法例如以下

  1. /**
  2. * bitmap旋转90度
  3. *
  4. * @param bitmap
  5. * @return
  6. */
  7. public static Bitmap createRotateBitmap(Bitmap bitmap) {
  8. if (bitmap != null) {
  9. Matrix m = new Matrix();
  10. try {
  11. m.setRotate(90, bitmap.getWidth() / 2, bitmap.getHeight() / 2);// 90就是我们须要选择的90度
  12. Bitmap bmp2 = Bitmap.createBitmap(bitmap, 0, 0,
  13. bitmap.getWidth(), bitmap.getHeight(), m, true);
  14. bitmap.recycle();
  15. bitmap = bmp2;
  16. } catch (Exception ex) {
  17. System.out.print("创建图片失败!" + ex);
  18. }
  19. }
  20. return bitmap;
  21. }

三.实例给出整个效果的具体代码

1.效果图

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTEyM2RlbWk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

2.布局文件activity_main.xml

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5.  
  6. <LinearLayout
  7. android:id="@+id/id_insert_btns_ll"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:layout_alignParentTop="true"
  11. android:orientation="horizontal" >
  12.  
  13. <Button
  14. android:id="@+id/id_local_img_btn"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_weight="1"
  18. android:text="插入本地图片" />
  19.  
  20. <Button
  21. android:id="@+id/id_camera_img_btn"
  22. android:layout_width="wrap_content"
  23. android:layout_height="wrap_content"
  24. android:layout_weight="1"
  25. android:text="插入拍照图片" />
  26. </LinearLayout>
  27.  
  28. <TextView
  29. android:id="@+id/id_show_url_tv"
  30. android:layout_width="match_parent"
  31. android:layout_height="wrap_content"
  32. android:gravity="center"
  33. android:layout_alignParentBottom="true"
  34. android:textColor="#FF0000"
  35. android:text="显示图片路径" />
  36.  
  37. <ImageView
  38. android:id="@+id/id_image_iv"
  39. android:layout_width="wrap_content"
  40. android:layout_height="wrap_content"
  41. android:layout_below="@id/id_insert_btns_ll"
  42. android:layout_above="@id/id_show_url_tv"
  43. android:layout_centerHorizontal="true"
  44. />
  45. </RelativeLayout>

3.主类文件MainActivity.java

  1. package com.example.insertimagedemo;
  2.  
  3. import java.io.File;
  4. import java.util.Calendar;
  5.  
  6. import android.app.Activity;
  7. import android.content.Intent;
  8. import android.graphics.Bitmap;
  9. import android.net.Uri;
  10. import android.os.Bundle;
  11. import android.os.Environment;
  12. import android.provider.MediaStore;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.view.View.OnClickListener;
  16. import android.widget.Button;
  17. import android.widget.ImageView;
  18. import android.widget.TextView;
  19. import android.widget.Toast;
  20.  
  21. public class MainActivity extends Activity implements OnClickListener {
  22.  
  23. private static final int LOCAL_IMAGE_CODE = 1;
  24. private static final int CAMERA_IMAGE_CODE = 2;
  25. private static final String IMAGE_TYPE = "image/*";
  26. private String rootUrl = null;
  27. private String curFormatDateStr = null;
  28.  
  29. private Button localImgBtn, cameraImgBtn;
  30. private TextView showUrlTv;
  31. private ImageView showImageIv;
  32.  
  33. @Override
  34. protected void onCreate(Bundle savedInstanceState) {
  35. super.onCreate(savedInstanceState);
  36. setContentView(R.layout.activity_main);
  37. findById();
  38. initData();
  39. }
  40.  
  41. /**
  42. * 初始化view
  43. */
  44. private void findById() {
  45. localImgBtn = (Button) this.findViewById(R.id.id_local_img_btn);
  46. cameraImgBtn = (Button) this.findViewById(R.id.id_camera_img_btn);
  47. showUrlTv = (TextView) this.findViewById(R.id.id_show_url_tv);
  48. showImageIv = (ImageView) this.findViewById(R.id.id_image_iv);
  49.  
  50. localImgBtn.setOnClickListener(this);
  51. cameraImgBtn.setOnClickListener(this);
  52. }
  53.  
  54. /**
  55. * 初始化相关data
  56. */
  57. private void initData() {
  58. rootUrl = Environment.getExternalStorageDirectory().getPath();
  59. }
  60.  
  61. @Override
  62. public void onClick(View v) {
  63. switch (v.getId()) {
  64. case R.id.id_local_img_btn:
  65. processLocal();
  66. break;
  67. case R.id.id_camera_img_btn:
  68. processCamera();
  69. break;
  70. }
  71. }
  72.  
  73. /**
  74. * 处理本地图片btn事件
  75. */
  76. private void processLocal() {
  77. Intent intent = new Intent();
  78. /* 开启Pictures画面Type设定为image */
  79. intent.setType(IMAGE_TYPE);
  80. /* 使用Intent.ACTION_GET_CONTENT这个Action */
  81. intent.setAction(Intent.ACTION_GET_CONTENT);
  82. /* 取得相片后返回本画面 */
  83. startActivityForResult(intent, LOCAL_IMAGE_CODE);
  84. }
  85.  
  86. /**
  87. * 处理camera图片btn事件
  88. */
  89. private void processCamera() {
  90. curFormatDateStr = HelpUtil.getDateFormatString(Calendar.getInstance()
  91. .getTime());
  92. String fileName = "IMG_" + curFormatDateStr + ".png";
  93. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  94. intent.putExtra(MediaStore.EXTRA_OUTPUT,
  95. Uri.fromFile(new File(rootUrl, fileName)));
  96. intent.putExtra("fileName", fileName);
  97. startActivityForResult(intent, CAMERA_IMAGE_CODE);
  98. }
  99.  
  100. /**
  101. * 处理Activity跳转后返回事件
  102. */
  103. @Override
  104. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  105. if (resultCode == RESULT_OK) {
  106. String url = "";
  107. Bitmap bitmap = null;
  108. if (requestCode == LOCAL_IMAGE_CODE) {
  109. Uri uri = data.getData();
  110. url = uri.toString().substring(
  111. uri.toString().indexOf("///") + 2);
  112. Log.e("uri", uri.toString());
  113. if (url.contains(".jpg") && url.contains(".png")) {
  114. Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
  115. return;
  116. }
  117. bitmap = HelpUtil.getBitmapByUrl(url);
  118. showImageIv.setImageBitmap(HelpUtil.getBitmapByUrl(url));
  119.  
  120. /**
  121. * 获取bitmap还有一种方法
  122. *
  123. * ContentResolver cr = this.getContentResolver(); bitmap =
  124. * HelpUtil.getBitmapByUri(uri, cr);
  125. */
  126.  
  127. } else if (requestCode == CAMERA_IMAGE_CODE) {
  128. url = rootUrl + "/" + "IMG_" + curFormatDateStr + ".png";
  129. bitmap = HelpUtil.getBitmapByUrl(url);
  130. showImageIv.setImageBitmap(HelpUtil.createRotateBitmap(bitmap));
  131.  
  132. /**
  133. * 获取bitmap还有一种方法
  134. *
  135. * File picture = new File(url);
  136. * Uri uri = Uri.fromFile(picture);
  137. * ContentResolver cr = this.getContentResolver();
  138. * bitmap = HelpUtil.getBitmapByUri(uri, cr);
  139. */
  140. }
  141.  
  142. showUrlTv.setText(url);
  143. } else {
  144. Toast.makeText(this, "没有加入图片", Toast.LENGTH_SHORT).show();
  145. }
  146.  
  147. }
  148. }

4.帮助类文件HelpUtil.java

  1. package com.example.insertimagedemo;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8.  
  9. import android.annotation.SuppressLint;
  10. import android.content.ContentResolver;
  11. import android.graphics.Bitmap;
  12. import android.graphics.BitmapFactory;
  13. import android.graphics.Matrix;
  14. import android.net.Uri;
  15.  
  16. public class HelpUtil {
  17. /**
  18. * 依据图片路径获取本地图片的Bitmap
  19. *
  20. * @param url
  21. * @return
  22. */
  23. public static Bitmap getBitmapByUrl(String url) {
  24. FileInputStream fis = null;
  25. Bitmap bitmap = null;
  26. try {
  27. fis = new FileInputStream(url);
  28. bitmap = BitmapFactory.decodeStream(fis);
  29.  
  30. } catch (FileNotFoundException e) {
  31. // TODO Auto-generated catch block
  32. e.printStackTrace();
  33. bitmap = null;
  34. } finally {
  35. if (fis != null) {
  36. try {
  37. fis.close();
  38. } catch (IOException e) {
  39. // TODO Auto-generated catch block
  40. e.printStackTrace();
  41. }
  42. fis = null;
  43. }
  44. }
  45.  
  46. return bitmap;
  47. }
  48.  
  49. /**
  50. * bitmap旋转90度
  51. *
  52. * @param bitmap
  53. * @return
  54. */
  55. public static Bitmap createRotateBitmap(Bitmap bitmap) {
  56. if (bitmap != null) {
  57. Matrix m = new Matrix();
  58. try {
  59. m.setRotate(90, bitmap.getWidth() / 2, bitmap.getHeight() / 2);// 90就是我们须要选择的90度
  60. Bitmap bmp2 = Bitmap.createBitmap(bitmap, 0, 0,
  61. bitmap.getWidth(), bitmap.getHeight(), m, true);
  62. bitmap.recycle();
  63. bitmap = bmp2;
  64. } catch (Exception ex) {
  65. System.out.print("创建图片失败。" + ex);
  66. }
  67. }
  68. return bitmap;
  69. }
  70.  
  71. public static Bitmap getBitmapByUri(Uri uri,ContentResolver cr){
  72. Bitmap bitmap = null;
  73. try {
  74. bitmap = BitmapFactory.decodeStream(cr
  75. .openInputStream(uri));
  76. } catch (FileNotFoundException e) {
  77. // TODO Auto-generated catch block
  78. e.printStackTrace();
  79. bitmap = null;
  80. }
  81. return bitmap;
  82. }
  83.  
  84. /**
  85. * 获取格式化日期字符串
  86. * @param date
  87. * @return
  88. */
  89. @SuppressLint("SimpleDateFormat")
  90. public static String getDateFormatString(Date date) {
  91. if (date == null)
  92. date = new Date();
  93. String formatStr = new String();
  94. SimpleDateFormat matter = new SimpleDateFormat("yyyyMMdd_HHmmss");
  95. formatStr = matter.format(date);
  96. return formatStr;
  97. }
  98. }

曾经就是本博文全部内容,谢谢品读。

源代码地址:http://download.csdn.net/detail/a123demi/8027697

Android 实例解说加入本地图片和调用系统拍照图片的更多相关文章

  1. Java乔晓松-android中调用系统拍照功能并显示拍照的图片

    android中调用系统拍照功能并显示拍照的图片 如果你是拍照完,利用onActivityResult获取data数据,把data数据转换成Bitmap数据,这样获取到的图片,是拍照的照片的缩略图 代 ...

  2. Android上传图片之调用系统拍照和从相冊选择图片

    Android上传图片之调用系统拍照和从相冊选择图片 本篇文章已授权微信公众号 guolin_blog (郭霖)独家公布 前言: 万丈高楼平底起,万事起于微末.不知不觉距离上篇博文已近四个月,2015 ...

  3. Android调用系统拍照裁剪和选图功能

    最近项目中用到修改用户头像的功能,基本上都是模板代码,现在简单记录一下. 调用系统拍照 private fun openCamera() { //调用相机拍照 // 创建File对象,用于存储拍照后的 ...

  4. 摄像头(3)调用系统拍照activity来拍照

    import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager ...

  5. 摄像头(2)调用系统拍照activity来录像

    import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager ...

  6. HTML5: 实现调用系统拍照或者选择照片并预览

    ylbtech-HTML5: 实现调用系统拍照或者选择照片并预览 1.返回顶部 1. <!DOCTYPE html> <html> <head> <meta ...

  7. android 7.0以上共享文件(解决调用系统照相和图片剪切出现的FileUriExposedException崩溃问题)

    在android7.0开始试共享“file://”URI 将会导致引发 FileUriExposedException. 如果应用需要与其他应用共享私有文件,则应该使用 FileProvider, F ...

  8. 关于android中调用系统拍照,返回图片是旋转90度

    转载博客:http://blog.csdn.net/walker02/article/details/8211628 项目开发中遇到的一个问题,对于三星手机在做手机照片选择时出现图片显示不正常,研究后 ...

  9. c# 调用系统默认图片浏览器打开图片

    private void OpenImage(string fileName) { try { Process.Start(fileName); } catch (Exception ex) { // ...

随机推荐

  1. 【LeetCode】Two Sum(两数之和)

    这道题是LeetCode里的第1道题. 题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会 ...

  2. NYOJ 814 又见拦截导弹

    又见拦截导弹 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 大家对拦截导弹那个题目应该比较熟悉了,我再叙述一下题意:某国为了防御敌国的导弹袭击,新研制出来一种导弹拦 ...

  3. 九度oj 题目1017:还是畅通工程

    题目描述:     某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离.省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可 ...

  4. JavaWeb基础(HTML)

    代码改变世界 HTML HTML是指超本标记语言,它不是编程语言,而是一种标记语言.标记语言是一套标记标签,HTML使用标记标签来描述网页,用以定义如何在页面上展示信息. 1.HTML标签 HTML标 ...

  5. Python之注册表增删改查(干货)

    在Windows平台下,对注册表的增删改查的需求比较多,微软提供了很多用于访问,修改注册表等的API,我们可以使用诸如bat,或者C++等各种方式去访问修改注册表.无所不能的python下如何完成这些 ...

  6. 【Luogu】P1602Sramoc问题(堆)

    题目链接 很巧妙的想法.一开始将1~k-1加入堆中,然后每次从堆里取出一个最小的,判断是不是答案,如果不是,那么就枚举新数的末一位加上. 代码如下 #include<cstdio> #in ...

  7. 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 ...

  8. 【树状数组区间修改单点查询】HDU 4031 Attack

    http://acm.hdu.edu.cn/showproblem.php?pid=4031 [题意] 有一个长为n的长城,进行q次操作,d为防护罩的冷却时间,Attack表示区间a-b的墙将在1秒后 ...

  9. 【扫描线或树状数组】CSU 1335 高桥和低桥

    http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1335 [题意] 给定n座桥的高度,给定m次洪水每次的涨水水位ai和退水水位bi 询问有多少座桥 ...

  10. 【2018.10.15】WZJ笔记(数论)

    1. 证明:对于任意质数$p\gt 3$,$p^2-1$能被$24$整除. 证:平方差公式,$p^2-1 = (p-1)(p+1)$. 再把$24$分解质因数$2^3*3$. 三个相邻的自然数中至少有 ...