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";@Overrideprotected 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);}@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubmPopupWindow.dismiss();}});}}@Overrideprotected 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;}@Overrideprotected 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"?>                                                                                


layout_login_choose_photo.xml

<?xml version="1.0" encoding="utf-8"?>        

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 param)throws Exception {HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(url);if (param != null && param.size() > 0) {List nameValuePairs = new ArrayList(param.size());Set 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 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 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存储,以及调用系统相机,相册。上传服务器权限也有了。只是我没服务器测试。

                        


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

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

 

更多相关文章

  1. Android 渗透测试学习手册 第三章 Android 应用的逆向和审计
  2. 在 Android 设备上搭建 Web 服务器
  3. Android客户端与服务器交互方式(1)
  4. android网络连接使用GET方式请求服务器时的setDoOutput(true)惹
  5. Monkey测试结果解析(二)
  6. Android Fragment页打开相册
  7. (Android下使用)Google Test C++单元测试框架(二)

随机推荐

  1. Android(安卓)scaleType属性与ImagView中
  2. android如何实现类似ios点击状态栏回到顶
  3. Android图像滤镜框架GPUImage从配置到应
  4. android 内部文件读取
  5. 请确保您的Android智能手机安全
  6. Android(安卓)Intent机制实例详解
  7. android 修改AVD的存放位置
  8. Android-自定义滑动菜单(抽屉效果)
  9. android Handler机制源码详解
  10. 王家林的81门一站式云计算分布式大数据&