Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android完美實現 拍照 選擇圖片 剪裁等代碼分享

android完美實現 拍照 選擇圖片 剪裁等代碼分享

編輯:關於Android編程

前言,版本兼容問題主要是由於4.4以前和4.4以後的Uri的格式不同所造成的錯誤

1.拍照 和選擇圖片
  ①選擇圖片

 intent = new Intent(Intent.ACTION_GET_CONTENT);
       intent.setType("image/*");
       startActivityForResult(intent, GALLERY_REQUEST_CODE);

  ②拍照

 intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
       startActivityForResult(intent, CAMERA_REQUEST_CODE);

2.獲取系統傳來的值

標記符

 private static int CAMERA_REQUEST_CODE = 1;
 private static int GALLERY_REQUEST_CODE = 2;
 private static int CROP_REQUEST_CODE = 3;



 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == CAMERA_REQUEST_CODE) {
     if (data == null) {
       return;
     } else { //拍照
       Bundle extras = data.getExtras();
       if (extras != null) {
         Bitmap bm = extras.getParcelable("data");
         Uri uri = saveBitmap(bm);
         startImageZoom(uri);
       }
     }
   } else if (requestCode == GALLERY_REQUEST_CODE) {
     if (data == null) {//相冊
       return;
     }
     Uri uri;
     uri = data.getData();
     Uri fileUri = convertUri(uri);
     startImageZoom(fileUri);
   } else if (requestCode == CROP_REQUEST_CODE) {
     if (data == null) {
       return;
     }//剪裁後的圖片
     Bundle extras = data.getExtras();
     if (extras == null) {
       return;
     }
     Bitmap bm = extras.getParcelable("data");
     ShowImageView(bm);
   }
 }

3.圖片選取後 根據Url 轉成流 並保存

private Uri convertUri(Uri uri) {
    InputStream is = null;
    try {
      is = getContentResolver().openInputStream(uri);
      Bitmap bitmap = BitmapFactory.decodeStream(is);
      is.close();
      return saveBitmap(bitmap);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }

4.保存圖片 記得加權限

private Uri saveBitmap(Bitmap bm) {
    File tmpDir = new File(Environment.getExternalStorageDirectory()
        + "/xiaoxin");
    if (!tmpDir.exists()) {
      tmpDir.mkdir();
    }
    File img = new File(tmpDir.getAbsolutePath() + "love.png");
    try {
      FileOutputStream fos = new FileOutputStream(img);
      bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
      fos.flush();
      fos.close();
      Toast.makeText(MainActivity.this, "成功了", Toast.LENGTH_SHORT).show();
      return Uri.fromFile(img);
    } catch (FileNotFoundException e) {
      Toast.makeText(MainActivity.this, "失敗了", Toast.LENGTH_SHORT).show();
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      Toast.makeText(MainActivity.this, "失敗了", Toast.LENGTH_SHORT).show();
      return null;
    }

  }

5.剪裁圖片

/**
   * 剪裁圖片
   * 
   * @param uri
   */
  private void startImageZoom(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 150);
    intent.putExtra("outputY", 150);
    intent.putExtra("return-data", true);
    startActivityForResult(intent, CROP_REQUEST_CODE);
  }

下面我們再來看一個實例:先是代碼的部分,部分是從網路上摘錄的,自己整理後當做工具類使用

配置文件:布局很簡單,一個ImageButton和一個Button,點擊都可以實現圖像選擇的功能,具體的實現根據大家在實際中用的效果而定
—————————————————————————————————————————————————
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.cogent.piccut"
  android:versionCode="1"
  android:versionName="1.0" >
 
  <uses-sdk android:minSdkVersion="10" />
 
  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
      android:label="@string/app_name"
      android:name=".PicCutActivity"
      android:screenOrientation="portrait" >
      <intent-filter >
        <action android:name="android.intent.action.MAIN" />
 
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
 
</manifest>

—————————————————————————————————————————————————
Java代碼:

package com.cogent.piccut;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;

public class PicCutActivity extends Activity implements OnClickListener {
  private ImageButton img_btn;
  private Button btn;
  private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
  private static final int PHOTO_REQUEST_GALLERY = 2;// 從相冊中選擇
  private static final int PHOTO_REQUEST_CUT = 3;// 結果
  // 創建一個以當前時間為名稱的文件
  File tempFile = new File(Environment.getExternalStorageDirectory(),getPhotoFileName());

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    init();
  }

  //初始化控件
  private void init() {
    img_btn = (ImageButton) findViewById(R.id.img_btn);
    btn = (Button) findViewById(R.id.btn);
    
    //為ImageButton和Button添加監聽事件
    img_btn.setOnClickListener(this);
    btn.setOnClickListener(this);
  }

  //點擊事件
  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.img_btn:
      showDialog();
      break;

    case R.id.btn:
      showDialog();
      break;
    }

  }

  
  //提示對話框方法
  private void showDialog() {
    new AlertDialog.Builder(this)
        .setTitle("頭像設置")
        .setPositiveButton("拍照", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.dismiss();
            // 調用系統的拍照功能
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 指定調用相機拍照後照片的儲存路徑
            intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(tempFile));
            startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
          }
        })
        .setNegativeButton("相冊", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.dismiss();
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
            startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
          }
        }).show();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub

    switch (requestCode) {
    case PHOTO_REQUEST_TAKEPHOTO:
      startPhotoZoom(Uri.fromFile(tempFile), 150);
      break;

    case PHOTO_REQUEST_GALLERY:
      if (data != null)
        startPhotoZoom(data.getData(), 150);
      break;

    case PHOTO_REQUEST_CUT:
      if (data != null) 
        setPicToView(data);
      break;
    }
    super.onActivityResult(requestCode, resultCode, data);

  }

  private void startPhotoZoom(Uri uri, int size) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    // crop為true是設置在開啟的intent中設置顯示的view可以剪裁
    intent.putExtra("crop", "true");

    // aspectX aspectY 是寬高的比例
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);

    // outputX,outputY 是剪裁圖片的寬高
    intent.putExtra("outputX", size);
    intent.putExtra("outputY", size);
    intent.putExtra("return-data", true);

    startActivityForResult(intent, PHOTO_REQUEST_CUT);
  }

  //將進行剪裁後的圖片顯示到UI界面上
  private void setPicToView(Intent picdata) {
    Bundle bundle = picdata.getExtras();
    if (bundle != null) {
      Bitmap photo = bundle.getParcelable("data");
      Drawable drawable = new BitmapDrawable(photo);
      img_btn.setBackgroundDrawable(drawable);
    }
  }

  // 使用系統當前日期加以調整作為照片的名稱
  private String getPhotoFileName() {
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
    return dateFormat.format(date) + ".jpg";
  }
}

心得總結:Androi系統內部自帶了圖片的剪裁功能,開發是只要調用即可,Intent的很多用法比較實用,但是太多了,需要用到的時候去查詢或者平時多看看官方文檔,很多代碼看著簡單但還是要實際自己去寫更好些,理解的更深入一些。

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