zoukankan      html  css  js  c++  java
  • 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.效果图


    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

  • 相关阅读:
    转: React系统的入门系统
    转: Android官方培训课程中文版(v0.9.5)
    释放Linux系统缓存
    Hyperledger Fabric1.0环境搭建
    JS中的call、apply、bind
    资产和负债
    JS以指定格式获取当前日期
    apache2.4配置ssl
    Apache2.4整合tomcat8
    使用JDK将tomcat变成https访问
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/6886148.html
Copyright © 2011-2022 走看看