实现调用Android手机的拍照功能

一、布局文件 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/more"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/grey"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:background="@color/black" >

        <LinearLayout
            android:id="@+id/top"
            android:layout_width="fill_parent"
            android:layout_height="@dimen/title_height"
            android:background="@drawable/top_bg2"
            android:gravity="center_vertical" >

            <Button
                android:id="@+id/more_back_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:background="@drawable/top_r_nom"
                android:text="返回"
                android:textColor="@android:color/white" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="@dimen/title_height"
                android:layout_weight="1"
                android:gravity="center" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="设置"
                    android:textColor="@android:color/white"
                    android:textSize="20sp" />
            </LinearLayout>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:background="@drawable/top_r_nom"
                android:text="确定"
                android:textColor="@android:color/white"
                android:visibility="invisible" />
        </LinearLayout>
    </LinearLayout>

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="1dp"
                android:layout_marginTop="6dp"
                android:background="@color/line_color"
                android:orientation="vertical" >
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@color/white"
                android:orientation="vertical" >

                <RelativeLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp" >

                    <ImageView
                        android:id="@+id/tx_arrow_iv"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:layout_marginRight="10dp"
                        android:src="@drawable/group_more" />

                    <ImageView
                        android:id="@+id/more_person_photo_setting_iv"
                        android:layout_width="63dp"
                        android:layout_height="63dp"
                        android:layout_alignParentLeft="true"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="20dp"
                        android:scaleType="fitXY"
                        android:src="@drawable/touxiang_tou1" />

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="fill_parent"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="15dp"
                        android:layout_toRightOf="@id/more_person_photo_setting_iv"
                        android:orientation="vertical" >

                        <TextView
                            android:id="@+id/more_person_name_tv"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="wenbing"
                            android:textColor="@color/black"
                            android:textSize="18sp" />

                        <TextView
                            android:id="@+id/more_person_account_tv"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="10dp"
                            android:text="15221364543" />
                    </LinearLayout>
                </RelativeLayout>
                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="1dp"
                    android:background="@color/line_color"
                    android:orientation="vertical" >
                </LinearLayout>
            </LinearLayout>

            <Button
                android:id="@+id/logout"
                android:layout_width="fill_parent"
                android:layout_height="38dp"
                android:layout_margin="15dp"
                android:layout_marginBottom="20dp"
                android:background="@drawable/longbtn1"
                android:text="注销并退出"
                android:textColor="@color/white"
                android:textSize="16sp" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>

二、activity 文件

package com.devdiv.test.bitmap_test;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
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.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MoreActivity extends Activity implements OnClickListener {

 private ImageView mPersonPhotoIv;

 /**
  * 对话框创建器
  */
 private AlertDialog.Builder builder;

 /**
  * 拍照作为头像的文件
  */
 private File cameraFile;

 /**
  * 拍照或者本地文件中的图像
  */
 private Bitmap headBitmap;

 private String mUserAccount;

 private File mPhotoPath;

 private Button backBtn;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  this.setContentView(R.layout.activity_more);
  initData();
  initView();
 }

 private void initView() {
  mPersonPhotoIv.setOnClickListener(this);
  this.findViewById(R.id.logout).setOnClickListener(this);
  ((TextView) this.findViewById(R.id.more_person_account_tv))
    .setText(mUserAccount);
  ((TextView) this.findViewById(R.id.more_person_name_tv))
    .setText("杨聪聪");
  mPersonPhotoIv.setImageResource(R.drawable.touxiang_tou1);
  backBtn = (Button) findViewById(R.id.more_back_btn);
  backBtn.setOnClickListener(this);
 }

 private void initData() {
  
  mUserAccount="123232323233";
  
  mPersonPhotoIv = (ImageView) this
    .findViewById(R.id.more_person_photo_setting_iv);
  mPhotoPath = new File(Environment
    .getExternalStorageDirectory().getAbsolutePath() + "/.V_WeChat_GA/" + "Avatar/");
  if (!mPhotoPath.exists())
   mPhotoPath.mkdirs();
  String path = mPhotoPath.getAbsolutePath() + File.separator + mUserAccount + ".jpg";
  cameraFile = new File(path);
 }

 @Override
 public void onClick(View v) {
  switch (v.getId()) {
  // 个人头像设计
  case R.id.more_person_photo_setting_iv:
   choiceHeadImage();
   break;
  case R.id.logout:
   break;
  }

 }

 private void choiceHeadImage() {
  builder = new AlertDialog.Builder(this);
  builder.setTitle("")
    .setIcon(android.R.drawable.ic_dialog_info)
    .setItems(R.array.headImageList,//<string-array name="headImageList"><item>拍照</item><item>相册</item></string-array>
      new DialogInterface.OnClickListener() {

       @Override
       public void onClick(DialogInterface dialog,
         int which) {
        switch (which) {
        case 0:
         /**
          * 拍照
          */
         getHeadFromCamera();
         break;

        case 1:
         /**
          * 去相册
          */
         getHeadFromAlbum();
         break;

        default:
         break;
        }
       }
      }).create().show();
 }

 /**
  * <拍照获取头像>
  */
 private void getHeadFromCamera() {
  /** 拍照第一步:首先判断SDCard是否存在 */
  String sdPath = Environment.getExternalStorageDirectory()
    .getAbsolutePath();
  if (null == sdPath) {
   /** 拍照第二步:如果sdcard不存在 */
   Toast.makeText(this, "SDCard不存在,无法拍照", Toast.LENGTH_SHORT).show();
   return;
  }
  /* 调用系统自带的照相意图 */
  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  /* 将拍照的图片保存到sd卡中或者内存中 */
  intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
  startActivityForResult(intent, 1);
 }

 /**
  * <从相册或文件中获取头像>
  */
 private void getHeadFromAlbum() {
  Intent intent = new Intent();
  intent.setType("image/*");
  intent.setAction(Intent.ACTION_GET_CONTENT);
  startActivityForResult(intent, 2);
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == 1 && resultCode == RESULT_OK) {
   /**
    * 拍照回调
    */
   try {
    Intent intentScan = new Intent(
      Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    sendBroadcast(intentScan);
    final Intent intent = getCropImageIntent(Uri
      .fromFile(cameraFile));
    startActivityForResult(intent, 3);
   } catch (Exception e) {
   }
  } else if (requestCode == 3) {
   /**
    * 得到的裁剪后的photo的bitmap对象
    */
   if (null != data) {
    headBitmap = data.getParcelableExtra("data");
    if (null != headBitmap) {
     BufferedOutputStream bos = null;
     try {
      bos = new BufferedOutputStream(new FileOutputStream(
        cameraFile));
      headBitmap.compress(Bitmap.CompressFormat.PNG, 80, bos);
      bos.flush();
      bos.close();
      new SavePersonPhotoTask().execute();
     } catch (IOException e) {
     }
    } else {
    }
   } else {
   }

  } else if (requestCode == 2) {
   /**
    * 从相册选取图片作为头像
    */
   finishActivity(2);
   if (2 == requestCode && resultCode == RESULT_OK && null != data) {
    ContentResolver resolver = getContentResolver();
    Uri uri = data.getData();
    try {
     String[] proj = { MediaStore.Images.Media.DATA };

     // 好像是android多媒体数据库的封装接口,具体的看Android文档
     Cursor cursor = managedQuery(uri, proj, null, null, null);
     // 按我个人理解 这个是获得用户选择的图片的索引值
     int column_index = cursor
       .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
     // 将光标移至开头 ,这个很重要,不小心很容易引起越界
     cursor.moveToFirst();
     // 最后根据索引值获取图片路径
     String path = cursor.getString(column_index);
     File photoFile = new File(path);
     // headBitmap = MediaStore.Images.Media.getBitmap(resolver,
     // uri);
     Intent intentScan = new Intent(
       Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
     sendBroadcast(intentScan);
     final Intent intent = getCropImageIntent(Uri
       .fromFile(photoFile));
     startActivityForResult(intent, 3);
    } catch (Exception e) {
    }
   }
  }
  super.onActivityResult(requestCode, resultCode, data);
 }

 /***
  * Constructs an intent for image cropping.
  */
 public static Intent getCropImageIntent(Uri photoUri) {
  Intent intent = new Intent("com.android.camera.action.CROP");
  intent.setDataAndType(photoUri, "image/**");
  intent.putExtra("crop", "true");
  intent.putExtra("aspectX", 1);
  intent.putExtra("aspectY", 1);
  intent.putExtra("outputX", 77);
  intent.putExtra("outputY", 77);
  intent.putExtra("return-data", true);
  return intent;
 }

 /**
  * @author
  * @version
  * @param 保存头像到服务端方法
  * @return 返回提交成功失败等结果
  */

 class SavePersonPhotoTask extends AsyncTask<Void, Integer, String> {

  @Override
  protected String doInBackground(Void... params) {
   //上传到服务器
   // {"result":200,"resultMsg":"头像更换成功","avatar":"images/avatar/1390374143418.jpg"}
   String content = "{\"result\":200,\"resultMsg\":\"头像更换成功\",\"avatar\":\"images/avatar/1390374143418.jpg\"}";
   return content;
  }

  @Override
  protected void onPostExecute(String result) {
   super.onPostExecute(result);
   if (null == result) {
    Toast.makeText(MoreActivity.this, "头像设置失败", Toast.LENGTH_SHORT)
      .show();
    return;
   }
   try {
    JSONObject response = new JSONObject(result);
    if ("200".equals(response.getString("result"))) {

     RenameFile(response.getString("avatar"));
     int angle = readPictureDegree(cameraFile
       .getAbsolutePath());
     headBitmap = rotaingImageView(headBitmap, angle);
     mPersonPhotoIv.setImageBitmap(headBitmap);

     Intent intent = new Intent("com.roya.WeixinAddressActivity");
     MoreActivity.this.sendBroadcast(intent);

     intent = new Intent("com.roya.vwechat.V2");
     intent.putExtra("type", 3);
      MoreActivity.this.sendBroadcast(intent);

     Toast.makeText(MoreActivity.this, "头像设置成功",
       Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(MoreActivity.this, "头像设置失败",
       Toast.LENGTH_SHORT).show();
    }
   } catch (JSONException e) {
    e.printStackTrace();
   }
  }

 }

 /**
  * 重新命名文件
  */
 public void RenameFile(String name) {
  String newName;
  if (null != name)
   newName = name.substring(name.lastIndexOf("/")).replaceAll("/", "");
  else
   return;
  cameraFile.renameTo(new File(mPhotoPath.getAbsolutePath()
    + File.separator + newName));
 }

 /**
  * 读取图片属性:旋转的角度
  *
  * @param path
  *            图片绝对路径
  * @return degree旋转的角度
  */
 public static int readPictureDegree(String path) {
  int degree = 0;
  try {
   ExifInterface exifInterface = new ExifInterface(path);
   int orientation = exifInterface.getAttributeInt(
     ExifInterface.TAG_ORIENTATION,
     ExifInterface.ORIENTATION_NORMAL);
   switch (orientation) {
   case ExifInterface.ORIENTATION_ROTATE_90:
    degree = 90;
    break;
   case ExifInterface.ORIENTATION_ROTATE_180:
    degree = 180;
    break;
   case ExifInterface.ORIENTATION_ROTATE_270:
    degree = 270;
    break;
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  return degree;
 }

 private Bitmap rotaingImageView(Bitmap bitmap, int angle2) {
  // 旋转图片 动作
  Matrix matrix = new Matrix();
  matrix.postRotate(angle2);
  Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  // 创建新的图片
  return resizedBitmap;
 }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值