Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android相機、圖冊demo

Android相機、圖冊demo

編輯:關於Android編程

本文為大家分享了Android相機、圖冊基本demo,供大家參考,具體內容如下

package com.example.democamera;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;
 
public class MainActivity extends Activity {
 
  private ImageView iv;
  static final int gallery = 1, camera = 2;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    iv = (ImageView) findViewById(R.id.iv_picture);
  }
 
  /**
   * 啟動圖片畫廊
   * 
   * @param view
   */
  public void startGallery(View view) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, gallery);
 
  }
 
  /**
   * 啟動相機
   * 
   * @param view
   */
  public void startCamera(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 
    if (isSDExsit()) {
      /* 創建存放圖片文件夾 */
      File dir = new File(Environment.getExternalStorageDirectory()
          + "/my");
      if (!dir.exists())
        dir.mkdirs();
      /* 設置圖片參數 得到原尺寸的圖片 */
      File file = new File(dir, "aaa.jpg");
      intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
          Configuration.ORIENTATION_UNDEFINED);
      intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    }
 
    startActivityForResult(intent, camera);
 
  }
 
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
 
    switch (requestCode) {
    case gallery:
      /* 做判斷,防止返回報錯 */
      if (data != null) {
        /*
         * 三種方式處理URI
         */
        Uri uri = data.getData();
        iv.setImageURI(uri);
 
        Bitmap bitmap = BitmapFactory
            .decodeFile(getPathByUri(uri, this));
        iv.setImageBitmap(bitmap);
 
        Bitmap bitmap2 = getBitmapByUri(uri, this);
        iv.setImageBitmap(bitmap2);
      }
 
      break;
 
    case camera:
 
      if (data != null) {// 這是獲得縮略圖的方法
        Bitmap b = (Bitmap) data.getExtras().get("data");
        iv.setImageBitmap(b);
 
      } else {// 有sd卡得到圖片原圖
        Bitmap bitmap = BitmapFactory.decodeFile("sdcard/my/aaa.jpg");//直接這樣做會有發生OOM的風險,Demo簡單這麼處理
        iv.setImageBitmap(bitmap);
      }
      break;
    default:
      break;
    }
 
  }
 
  /**
   * Uri-->Bitmap
   * 
   * @param uri
   * @param context
   * @return
   */
  public static Bitmap getBitmapByUri(Uri uri, Context context) {
    Bitmap bitmap = null;
    try {
      bitmap = MediaStore.Images.Media.getBitmap(
          context.getContentResolver(), uri);
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
 
    return bitmap;
  }
 
  /**
   * Uri--->Path
   * 
   * @param uri
   * @param context
   * @return
   */
  public static String getPathByUri(Uri uri, Context context) {
    String path = null;
 
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver().query(uri, projection,
        null, null, null);
    if (cursor.moveToFirst()) {
      int index = cursor
          .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
      path = cursor.getString(index);
    }
    return path;
 
  }
 
  /**
   * 判斷SD卡是否存在
   * 
   * @return
   */
  public static boolean isSDExsit() {
    if (Environment.getExternalStorageState().equals(
        Environment.MEDIA_MOUNTED)) {
      return true;
    } else {
      return false;
    }
  }
 
}

下面分享具體Android 調用相機、打開相冊、裁剪圖片的實現代碼,內容如下

private ImageView iv_user_photo;
  private String fileName = "";
  private File tempFile;
  private int crop = 300;// 裁剪大小
  private static final int OPEN_CAMERA_CODE = 10;
  private static final int OPEN_GALLERY_CODE = 11;
  private static final int CROP_PHOTO_CODE = 12;


  private OnClickListener PopupWindowItemOnClick = new OnClickListener() {

    @Override
    public void onClick(View v) {
      menuWindow.dismiss();
      switch (v.getId()) {
      // 拍照
      case R.id.btn_camera:
        initFile();
        openCamera();
        break;
      // 相冊
      case R.id.btn_gallery:
        initFile();
        openGallery();
        break;
      default:
        break;
      }
    }
  };

  public void initFile() {
    if(fileName.equals("")) {
      if(FileUtil.existSDCard()) {
        String path = Environment.getExternalStorageDirectory() + File.separator + "JanuBookingOnline" + File.separator;
        FileUtil.mkdir(path);
        Logger.i("path:" + path);
        fileName = path + "user_head_photo.jpg";
        tempFile = new File(fileName);
      } else {
        CommonUitl.toast(context, "請插入SD卡");
      }
    }
  }

  /**
   * 調用相機
   */
  public void openCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 打開相機
    intent.putExtra("output", Uri.fromFile(tempFile));
    startActivityForResult(intent, OPEN_CAMERA_CODE);
  }

  /**
   * 打開相冊
   */
  public void openGallery() {
    Intent intent = new Intent(Intent.ACTION_PICK);// 打開相冊
    intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
    intent.putExtra("output", Uri.fromFile(tempFile));
    startActivityForResult(intent, OPEN_GALLERY_CODE);
  }

  /**
   * 裁剪圖片
   * @param uri
   */
  public void cropPhoto(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("output", Uri.fromFile(tempFile));
    intent.putExtra("crop", true);
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", crop);
    intent.putExtra("outputY", crop);
    startActivityForResult(intent, CROP_PHOTO_CODE);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == 1)
      return;

    switch (requestCode) {
    case OPEN_CAMERA_CODE:
      cropPhoto(Uri.fromFile(tempFile));
      break;
    case OPEN_GALLERY_CODE:
      cropPhoto(data.getData());
      break;
    case CROP_PHOTO_CODE:
      try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        Bitmap bitmap = BitmapFactory.decodeFile(fileName, options);

        if (bitmap != null) {
          iv_user_photo.setImageBitmap(bitmap);
          CommonUitl.sharedPreferences(context, AppConstants.USER_PHOTO, fileName);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      break;
    default:
      break;
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

以上就是關於Android相機、圖冊的基本操作內容,希望對大家學習Android軟件編程有所幫助。

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