Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 實例講解添加本地圖片和調用系統拍照圖片

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);
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.效果圖

\\

2.布局文件activity_main.xml



    

        

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

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved