码迷,mamicode.com
首页 > 移动开发 > 详细

Android 调用系统相机以及相册源码

时间:2015-04-12 10:44:04      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:android   bitmap   

Android 调用系统相机拍照、以及相册。完成之后图片是上传到app上。前面的功能已经测试过了。没有上传到服务器,因为我没服务器测试。但项目里面有个类可以参考上传图片到服务器,我就没测试了。接下来看代码,虽然注释写得少,但其作用看英文单词意思,又在或是查看调用。
项目源码下载地址:
http://download.csdn.net/detail/qq_16064871/8585169

转载请注明出处: http://blog.csdn.net/qq_16064871

package com.example.takephotodemo;

import java.io.File;
import java.io.IOException;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	private ImageView mimageViewPhotoShow;
	private PopupWindow mPopupWindow;
	private View mpopview;
	private Bitmap photo;
	private File mPhotoFile;
	private int CAMERA_RESULT = 100;
	private int RESULT_LOAD_IMAGE = 200;
	private String saveDir = Environment.getExternalStorageDirectory()
			.getPath() + "/temp_image";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		InitUI();
	}

	private void InitUI() {
		View buttonChoosePhoto = (Button) findViewById(R.id.buttonChoosePhoto);
		if (buttonChoosePhoto != null) {
			buttonChoosePhoto.setOnClickListener(this);
		}

		mimageViewPhotoShow = (ImageView) findViewById(R.id.imageViewPhotoShow);
	}

	@Override
	public void onClick(View arg0) {
		if (arg0.getId() == R.id.buttonChoosePhoto) {
			LayoutInflater inflater = LayoutInflater.from(this);
			mpopview = inflater.inflate(R.layout.layout_login_choose_photo,
					null);

			mPopupWindow = new PopupWindow(mpopview, 300, 400, true);
			mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tekephoto_dialog_background));

			mPopupWindow.showAtLocation(mimageViewPhotoShow, Gravity.CENTER, 0,
					0);
			Button mbuttonTakePhoto = (Button) mpopview
					.findViewById(R.id.button_take_photo);
			Button mbuttonChoicePhoto = (Button) mpopview
					.findViewById(R.id.button_choice_photo);
			Button mbuttonChoicecannce = (Button) mpopview
					.findViewById(R.id.button_choice_cancer);

			// 相册上传
			mbuttonChoicePhoto.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mPopupWindow.dismiss();
					Intent i = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(i, RESULT_LOAD_IMAGE);
				}
			});

			File savePath = new File(saveDir);
			if (!savePath.exists()) {
				savePath.mkdirs();
			}

			// 拍照上传
			mbuttonTakePhoto.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mPopupWindow.dismiss();
					destoryImage();
					String state = Environment.getExternalStorageState();
					if (state.equals(Environment.MEDIA_MOUNTED)) {
						mPhotoFile = new File(saveDir, "temp.jpg");
						mPhotoFile.delete();
						if (!mPhotoFile.exists()) {
							try {
								mPhotoFile.createNewFile();
							} catch (IOException e) {
								e.printStackTrace();
								Toast.makeText(getApplication(), "照片创建失败!",
										Toast.LENGTH_LONG).show();
								return;
							}
						}
						Intent intent = new Intent(
								"android.media.action.IMAGE_CAPTURE");
						intent.putExtra(MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(mPhotoFile));
						startActivityForResult(intent, CAMERA_RESULT);
					} else {
						Toast.makeText(getApplication(), "sdcard无效或没有插入!",
								Toast.LENGTH_SHORT).show();
					}
				}
			});

			mbuttonChoicecannce.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mPopupWindow.dismiss();
				}
			});
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAMERA_RESULT && resultCode == RESULT_OK) {
			if (mPhotoFile != null && mPhotoFile.exists()) {
				BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
				bitmapOptions.inSampleSize = 8;
				int degree = readPictureDegree(mPhotoFile.getAbsolutePath());
				Bitmap bitmap = BitmapFactory.decodeFile(mPhotoFile.getPath(),
						bitmapOptions);
				bitmap = rotaingImageView(degree, bitmap);
				mimageViewPhotoShow.setImageBitmap(bitmap);
			}
		}
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();

			mimageViewPhotoShow.setImageBitmap(BitmapFactory
					.decodeFile(picturePath));
		}
	}

	private 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 static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		System.out.println("angle2=" + angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}

	@Override
	protected void onDestroy() {
		destoryImage();
		super.onDestroy();
	}

	private void destoryImage() {
		if (photo != null) {
			photo.recycle();
			photo = null;
		}
	}
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="20dp" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="vertical" >

                <ImageView
                    android:id="@+id/imageViewPhotoShow"
                    android:layout_width="150dp"
                    android:layout_height="150dp"
                    android:layout_weight="1" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                 android:paddingTop="20dp"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/buttonChoosePhoto"
                    android:layout_width="100dp"
                    android:layout_height="40dp"
                    android:background="@drawable/btn_takephoto_background"
                    android:text="选择头像"
                    android:textColor="#eee"
                    android:textSize="16sp" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>


layout_login_choose_photo.xml

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

    <TextView
        android:id="@+id/textchoice"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:text="请选择获取头像方式:"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textSize="16sp" />

    <Button
        android:id="@+id/button_take_photo"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/btn_takephoto_background"
        android:text="拍照"
        android:textColor="#eee"
        android:textSize="16sp" />

    <Button
        android:id="@+id/button_choice_photo"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/btn_takephoto_background"
        android:text="从相册选择"
        android:textColor="#eee"
        android:textSize="16sp" />

    <Button
        android:id="@+id/button_choice_cancer"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/btn_takephoto_background"
        android:text="取消"
        android:textColor="#eee"
        android:textSize="16sp" />

</LinearLayout>

NetUtil这个类,我也是参考网上的,没测试过。是图片上传服务器的。

package com.example.takephotodemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class NetUtil {
	/**
	 * 以POST方式提交表单
	 * 
	 * @param url
	 *            服务器路径
	 * @param param
	 *            参数键值对
	 * @return 响应结果
	 * @throws Exception
	 */
	public static String doPost(String url, Map<String, Object> param)
			throws Exception {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		if (param != null && param.size() > 0) {
			List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(
					param.size());
			Set<String> keys = param.keySet();
			for (Object o : keys) {
				String key = (String) o;
				nameValuePairs.add(new BasicNameValuePair(key, String
						.valueOf(param.get(key))));
			}
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
		}
		HttpResponse response = client.execute(post);
		/** 返回状态 **/
		int statusCode = response.getStatusLine().getStatusCode();
		StringBuffer sb = new StringBuffer();
		if (statusCode == HttpStatus.SC_OK) {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						instream));
				String tempLine;
				while ((tempLine = br.readLine()) != null) {
					sb.append(tempLine);
				}
			}
		}
		post.abort();
		return sb.toString();
	}

	/**
	 * 
	 * 
	 * @param url
	 * @param param
	 * @param file
	 * @return 
	 * @throws Exception
	 */
	private String doPost(String url, Map<String, String> param, File file)
			throws Exception {
		HttpPost post = new HttpPost(url);

		HttpClient client = new DefaultHttpClient();
		MultipartEntity entity = new MultipartEntity();
		if (param != null && !param.isEmpty()) {
			for (Map.Entry<String, String> entry : param.entrySet()) {
				entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
			}
		}
		// 添加文件参数
		if (file != null && file.exists()) {
			entity.addPart("file", new FileBody(file));
		}
		post.setEntity(entity);
		HttpResponse response = client.execute(post);
		int stateCode = response.getStatusLine().getStatusCode();
		StringBuffer sb = new StringBuffer();
		if (stateCode == HttpStatus.SC_OK) {
			HttpEntity result = response.getEntity();
			if (result != null) {
				InputStream is = result.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String tempLine;
				while ((tempLine = br.readLine()) != null) {
					sb.append(tempLine);
				}
			}
		}
		post.abort();
		return sb.toString();
	}

	private String doGet(String url) {
		StringBuilder sb = new StringBuilder();
		try {
			HttpGet get = new HttpGet(url);
			// HttpPost post = new HttpPost(url);

			HttpClient client = new DefaultHttpClient();
			HttpResponse response = client.execute(get);
			StatusLine state = response.getStatusLine();
			if (state.getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity eneity = response.getEntity();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						eneity.getContent()));
				String content;
				while ((content = br.readLine()) != null) {
					sb.append(content);
				}
			}
			get.abort();
		} catch (Exception e) {
			e.printStackTrace();
			return sb.toString();
		}
		return sb.toString();
	}
}

记得加入权限,权限主要是访问sd存储,以及调用系统相机,相册。上传服务器权限也有了。只是我没服务器测试。

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


项目源码下载地址:http://download.csdn.net/detail/qq_16064871/8585169

转载请注明出处: http://blog.csdn.net/qq_16064871

 

Android 调用系统相机以及相册源码

标签:android   bitmap   

原文地址:http://blog.csdn.net/qq_16064871/article/details/45007469

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!