首页 > 代码库 > Android 实例讲解添加本地图片和调用系统拍照图片

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.

<span style="font-size:18px;"><span style="white-space:pre">	</span>url = rootUrl + "/" + "IMG_" + curFormatDateStr + ".png";
	bitmap = HelpUtil.getBitmapByUrl(url);
	showImageIv.setImageBitmap(HelpUtil.createRotateBitmap(bitmap));</span>

注意:由于拍照所得图片放在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.效果图


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;
	}
}

以前就是本博文所有内容,谢谢品读。

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

Android 实例讲解添加本地图片和调用系统拍照图片