Android 執行個體講解添加本地圖片和調用系統拍照圖片

來源:互聯網
上載者:User

標籤:本地圖片   系統拍照   startactivityforresu   onactivityresult   

在項目的開發過程我們離不開圖片,而有時候需要調用本地的圖片,有時候需要調用拍照圖片。同時實現拍照的方法有兩種,一種是調用系統拍照功能,另一種是自訂拍照功能。而本博文目前只講解第一種方法,第二種方法後期在加以講解。

添加本地圖片和調用系統拍照圖片主要是通過調用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;@Overrideprotected 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();}@Overridepublic 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跳轉後返回事件 */@Overridepublic 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 blocke.printStackTrace();bitmap = null;} finally {if (fis != null) {try {fis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.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 blocke.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 執行個體講解添加本地圖片和調用系統拍照圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.