zoukankan      html  css  js  c++  java
  • Android 调用系统相机以及相册源码

    转自http://blog.csdn.net/qq_16064871/article/details/45007469

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

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

    [java] view plaincopy
    1. package com.example.takephotodemo;  
    2.   
    3. import java.io.File;  
    4. import java.io.IOException;  
    5. import android.media.ExifInterface;  
    6. import android.net.Uri;  
    7. import android.os.Bundle;  
    8. import android.os.Environment;  
    9. import android.provider.MediaStore;  
    10. import android.app.Activity;  
    11. import android.content.Intent;  
    12. import android.database.Cursor;  
    13. import android.graphics.Bitmap;  
    14. import android.graphics.BitmapFactory;  
    15. import android.graphics.Matrix;  
    16. import android.view.Gravity;  
    17. import android.view.LayoutInflater;  
    18. import android.view.View;  
    19. import android.view.View.OnClickListener;  
    20. import android.widget.Button;  
    21. import android.widget.ImageView;  
    22. import android.widget.PopupWindow;  
    23. import android.widget.Toast;  
    24.   
    25. public class MainActivity extends Activity implements OnClickListener {  
    26.     private ImageView mimageViewPhotoShow;  
    27.     private PopupWindow mPopupWindow;  
    28.     private View mpopview;  
    29.     private Bitmap photo;  
    30.     private File mPhotoFile;  
    31.     private int CAMERA_RESULT = 100;  
    32.     private int RESULT_LOAD_IMAGE = 200;  
    33.     private String saveDir = Environment.getExternalStorageDirectory()  
    34.             .getPath() + "/temp_image";  
    35.   
    36.     @Override  
    37.     protected void onCreate(Bundle savedInstanceState) {  
    38.         super.onCreate(savedInstanceState);  
    39.         setContentView(R.layout.activity_main);  
    40.         InitUI();  
    41.     }  
    42.   
    43.     private void InitUI() {  
    44.         View buttonChoosePhoto = (Button) findViewById(R.id.buttonChoosePhoto);  
    45.         if (buttonChoosePhoto != null) {  
    46.             buttonChoosePhoto.setOnClickListener(this);  
    47.         }  
    48.   
    49.         mimageViewPhotoShow = (ImageView) findViewById(R.id.imageViewPhotoShow);  
    50.     }  
    51.   
    52.     @Override  
    53.     public void onClick(View arg0) {  
    54.         if (arg0.getId() == R.id.buttonChoosePhoto) {  
    55.             LayoutInflater inflater = LayoutInflater.from(this);  
    56.             mpopview = inflater.inflate(R.layout.layout_login_choose_photo,  
    57.                     null);  
    58.   
    59.             mPopupWindow = new PopupWindow(mpopview, 300400true);  
    60.             mPopupWindow.setBackgroundDrawable(getResources().getDrawable(  
    61.                     R.drawable.tekephoto_dialog_background));  
    62.   
    63.             mPopupWindow.showAtLocation(mimageViewPhotoShow, Gravity.CENTER, 0,  
    64.                     0);  
    65.             Button mbuttonTakePhoto = (Button) mpopview  
    66.                     .findViewById(R.id.button_take_photo);  
    67.             Button mbuttonChoicePhoto = (Button) mpopview  
    68.                     .findViewById(R.id.button_choice_photo);  
    69.             Button mbuttonChoicecannce = (Button) mpopview  
    70.                     .findViewById(R.id.button_choice_cancer);  
    71.   
    72.             // 相册上传  
    73.             mbuttonChoicePhoto.setOnClickListener(new OnClickListener() {  
    74.                 @Override  
    75.                 public void onClick(View v) {  
    76.                     mPopupWindow.dismiss();  
    77.                     Intent i = new Intent(  
    78.                             Intent.ACTION_PICK,  
    79.                             android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
    80.                     startActivityForResult(i, RESULT_LOAD_IMAGE);  
    81.                 }  
    82.             });  
    83.   
    84.             File savePath = new File(saveDir);  
    85.             if (!savePath.exists()) {  
    86.                 savePath.mkdirs();  
    87.             }  
    88.   
    89.             // 拍照上传  
    90.             mbuttonTakePhoto.setOnClickListener(new OnClickListener() {  
    91.                 @Override  
    92.                 public void onClick(View v) {  
    93.                     mPopupWindow.dismiss();  
    94.                     destoryImage();  
    95.                     String state = Environment.getExternalStorageState();  
    96.                     if (state.equals(Environment.MEDIA_MOUNTED)) {  
    97.                         mPhotoFile = new File(saveDir, "temp.jpg");  
    98.                         mPhotoFile.delete();  
    99.                         if (!mPhotoFile.exists()) {  
    100.                             try {  
    101.                                 mPhotoFile.createNewFile();  
    102.                             } catch (IOException e) {  
    103.                                 e.printStackTrace();  
    104.                                 Toast.makeText(getApplication(), "照片创建失败!",  
    105.                                         Toast.LENGTH_LONG).show();  
    106.                                 return;  
    107.                             }  
    108.                         }  
    109.                         Intent intent = new Intent(  
    110.                                 "android.media.action.IMAGE_CAPTURE");  
    111.                         intent.putExtra(MediaStore.EXTRA_OUTPUT,  
    112.                                 Uri.fromFile(mPhotoFile));  
    113.                         startActivityForResult(intent, CAMERA_RESULT);  
    114.                     } else {  
    115.                         Toast.makeText(getApplication(), "sdcard无效或没有插入!",  
    116.                                 Toast.LENGTH_SHORT).show();  
    117.                     }  
    118.                 }  
    119.             });  
    120.   
    121.             mbuttonChoicecannce.setOnClickListener(new OnClickListener() {  
    122.                 @Override  
    123.                 public void onClick(View v) {  
    124.                     // TODO Auto-generated method stub  
    125.                     mPopupWindow.dismiss();  
    126.                 }  
    127.             });  
    128.         }  
    129.     }  
    130.   
    131.     @Override  
    132.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    133.         super.onActivityResult(requestCode, resultCode, data);  
    134.         if (requestCode == CAMERA_RESULT && resultCode == RESULT_OK) {  
    135.             if (mPhotoFile != null && mPhotoFile.exists()) {  
    136.                 BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();  
    137.                 bitmapOptions.inSampleSize = 8;  
    138.                 int degree = readPictureDegree(mPhotoFile.getAbsolutePath());  
    139.                 Bitmap bitmap = BitmapFactory.decodeFile(mPhotoFile.getPath(),  
    140.                         bitmapOptions);  
    141.                 bitmap = rotaingImageView(degree, bitmap);  
    142.                 mimageViewPhotoShow.setImageBitmap(bitmap);  
    143.             }  
    144.         }  
    145.         if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK  
    146.                 && null != data) {  
    147.             Uri selectedImage = data.getData();  
    148.             String[] filePathColumn = { MediaStore.Images.Media.DATA };  
    149.   
    150.             Cursor cursor = getContentResolver().query(selectedImage,  
    151.                     filePathColumn, nullnullnull);  
    152.             cursor.moveToFirst();  
    153.   
    154.             int columnIndex = cursor.getColumnIndex(filePathColumn[0]);  
    155.             String picturePath = cursor.getString(columnIndex);  
    156.             cursor.close();  
    157.   
    158.             mimageViewPhotoShow.setImageBitmap(BitmapFactory  
    159.                     .decodeFile(picturePath));  
    160.         }  
    161.     }  
    162.   
    163.     private static int readPictureDegree(String path) {  
    164.         int degree = 0;  
    165.         try {  
    166.             ExifInterface exifInterface = new ExifInterface(path);  
    167.             int orientation = exifInterface.getAttributeInt(  
    168.                     ExifInterface.TAG_ORIENTATION,  
    169.                     ExifInterface.ORIENTATION_NORMAL);  
    170.             switch (orientation) {  
    171.             case ExifInterface.ORIENTATION_ROTATE_90:  
    172.                 degree = 90;  
    173.                 break;  
    174.             case ExifInterface.ORIENTATION_ROTATE_180:  
    175.                 degree = 180;  
    176.                 break;  
    177.             case ExifInterface.ORIENTATION_ROTATE_270:  
    178.                 degree = 270;  
    179.                 break;  
    180.             }  
    181.         } catch (IOException e) {  
    182.             e.printStackTrace();  
    183.         }  
    184.         return degree;  
    185.     }  
    186.   
    187.     private static Bitmap rotaingImageView(int angle, Bitmap bitmap) {  
    188.         // 旋转图片 动作  
    189.         Matrix matrix = new Matrix();  
    190.         matrix.postRotate(angle);  
    191.         System.out.println("angle2=" + angle);  
    192.         // 创建新的图片  
    193.         Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 00,  
    194.                 bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
    195.         return resizedBitmap;  
    196.     }  
    197.   
    198.     @Override  
    199.     protected void onDestroy() {  
    200.         destoryImage();  
    201.         super.onDestroy();  
    202.     }  
    203.   
    204.     private void destoryImage() {  
    205.         if (photo != null) {  
    206.             photo.recycle();  
    207.             photo = null;  
    208.         }  
    209.     }  
    210. }  


    activity_main.xml

    [html] view plaincopy
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent"  
    5.     android:orientation="vertical" >  
    6.   
    7.     <ScrollView  
    8.         android:id="@+id/scrollView1"  
    9.         android:layout_width="match_parent"  
    10.         android:layout_height="wrap_content"  
    11.         android:layout_weight="1" >  
    12.   
    13.         <LinearLayout  
    14.             android:layout_width="match_parent"  
    15.             android:layout_height="match_parent"  
    16.             android:orientation="vertical"  
    17.             android:paddingTop="20dp" >  
    18.   
    19.             <LinearLayout  
    20.                 android:layout_width="match_parent"  
    21.                 android:layout_height="match_parent"  
    22.                 android:gravity="center"  
    23.                 android:orientation="vertical" >  
    24.   
    25.                 <ImageView  
    26.                     android:id="@+id/imageViewPhotoShow"  
    27.                     android:layout_width="150dp"  
    28.                     android:layout_height="150dp"  
    29.                     android:layout_weight="1" />  
    30.             </LinearLayout>  
    31.   
    32.             <LinearLayout  
    33.                 android:layout_width="match_parent"  
    34.                 android:layout_height="match_parent"  
    35.                 android:gravity="center"  
    36.                  android:paddingTop="20dp"  
    37.                 android:orientation="vertical" >  
    38.   
    39.                 <Button  
    40.                     android:id="@+id/buttonChoosePhoto"  
    41.                     android:layout_width="100dp"  
    42.                     android:layout_height="40dp"  
    43.                     android:background="@drawable/btn_takephoto_background"  
    44.                     android:text="选择头像"  
    45.                     android:textColor="#eee"  
    46.                     android:textSize="16sp" />  
    47.             </LinearLayout>  
    48.         </LinearLayout>  
    49.     </ScrollView>  
    50.   
    51. </LinearLayout>  


    layout_login_choose_photo.xml

    [html] view plaincopy
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:layout_width="fill_parent"  
    4.     android:layout_height="fill_parent"  
    5.     android:orientation="vertical" >  
    6.   
    7.     <TextView  
    8.         android:id="@+id/textchoice"  
    9.         android:layout_width="wrap_content"  
    10.         android:layout_height="40dp"  
    11.         android:layout_gravity="center_horizontal"  
    12.         android:gravity="center"  
    13.         android:text="请选择获取头像方式:"  
    14.         android:textAppearance="?android:attr/textAppearanceMedium"  
    15.         android:textSize="16sp" />  
    16.   
    17.     <Button  
    18.         android:id="@+id/button_take_photo"  
    19.         android:layout_width="match_parent"  
    20.         android:layout_height="40dp"  
    21.         android:layout_marginLeft="10dp"  
    22.         android:layout_marginRight="10dp"  
    23.         android:layout_marginTop="5dp"  
    24.         android:background="@drawable/btn_takephoto_background"  
    25.         android:text="拍照"  
    26.         android:textColor="#eee"  
    27.         android:textSize="16sp" />  
    28.   
    29.     <Button  
    30.         android:id="@+id/button_choice_photo"  
    31.         android:layout_width="match_parent"  
    32.         android:layout_height="40dp"  
    33.         android:layout_marginLeft="10dp"  
    34.         android:layout_marginRight="10dp"  
    35.         android:layout_marginTop="10dp"  
    36.         android:background="@drawable/btn_takephoto_background"  
    37.         android:text="从相册选择"  
    38.         android:textColor="#eee"  
    39.         android:textSize="16sp" />  
    40.   
    41.     <Button  
    42.         android:id="@+id/button_choice_cancer"  
    43.         android:layout_width="match_parent"  
    44.         android:layout_height="40dp"  
    45.         android:layout_marginLeft="10dp"  
    46.         android:layout_marginRight="10dp"  
    47.         android:layout_marginTop="10dp"  
    48.         android:background="@drawable/btn_takephoto_background"  
    49.         android:text="取消"  
    50.         android:textColor="#eee"  
    51.         android:textSize="16sp" />  
    52.   
    53. </LinearLayout>  

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

    [java] view plaincopy
    1. package com.example.takephotodemo;  
    2.   
    3. import java.io.BufferedReader;  
    4. import java.io.File;  
    5. import java.io.InputStream;  
    6. import java.io.InputStreamReader;  
    7. import java.util.ArrayList;  
    8. import java.util.List;  
    9. import java.util.Map;  
    10. import java.util.Set;  
    11. import org.apache.http.HttpEntity;  
    12. import org.apache.http.HttpResponse;  
    13. import org.apache.http.HttpStatus;  
    14. import org.apache.http.StatusLine;  
    15. import org.apache.http.client.HttpClient;  
    16. import org.apache.http.client.entity.UrlEncodedFormEntity;  
    17. import org.apache.http.client.methods.HttpGet;  
    18. import org.apache.http.client.methods.HttpPost;  
    19. import org.apache.http.entity.mime.MultipartEntity;  
    20. import org.apache.http.entity.mime.content.FileBody;  
    21. import org.apache.http.entity.mime.content.StringBody;  
    22. import org.apache.http.impl.client.DefaultHttpClient;  
    23. import org.apache.http.message.BasicNameValuePair;  
    24.   
    25. public class NetUtil {  
    26.     /** 
    27.      * 以POST方式提交表单 
    28.      *  
    29.      * @param url 
    30.      *            服务器路径 
    31.      * @param param 
    32.      *            参数键值对 
    33.      * @return 响应结果 
    34.      * @throws Exception 
    35.      */  
    36.     public static String doPost(String url, Map<String, Object> param)  
    37.             throws Exception {  
    38.         HttpClient client = new DefaultHttpClient();  
    39.         HttpPost post = new HttpPost(url);  
    40.         if (param != null && param.size() > 0) {  
    41.             List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(  
    42.                     param.size());  
    43.             Set<String> keys = param.keySet();  
    44.             for (Object o : keys) {  
    45.                 String key = (String) o;  
    46.                 nameValuePairs.add(new BasicNameValuePair(key, String  
    47.                         .valueOf(param.get(key))));  
    48.             }  
    49.             post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));  
    50.         }  
    51.         HttpResponse response = client.execute(post);  
    52.         /** 返回状态 **/  
    53.         int statusCode = response.getStatusLine().getStatusCode();  
    54.         StringBuffer sb = new StringBuffer();  
    55.         if (statusCode == HttpStatus.SC_OK) {  
    56.             HttpEntity entity = response.getEntity();  
    57.             if (entity != null) {  
    58.                 InputStream instream = entity.getContent();  
    59.                 BufferedReader br = new BufferedReader(new InputStreamReader(  
    60.                         instream));  
    61.                 String tempLine;  
    62.                 while ((tempLine = br.readLine()) != null) {  
    63.                     sb.append(tempLine);  
    64.                 }  
    65.             }  
    66.         }  
    67.         post.abort();  
    68.         return sb.toString();  
    69.     }  
    70.   
    71.     /** 
    72.      *  
    73.      *  
    74.      * @param url 
    75.      * @param param 
    76.      * @param file 
    77.      * @return  
    78.      * @throws Exception 
    79.      */  
    80.     private String doPost(String url, Map<String, String> param, File file)  
    81.             throws Exception {  
    82.         HttpPost post = new HttpPost(url);  
    83.   
    84.         HttpClient client = new DefaultHttpClient();  
    85.         MultipartEntity entity = new MultipartEntity();  
    86.         if (param != null && !param.isEmpty()) {  
    87.             for (Map.Entry<String, String> entry : param.entrySet()) {  
    88.                 entity.addPart(entry.getKey(), new StringBody(entry.getValue()));  
    89.             }  
    90.         }  
    91.         // 添加文件参数  
    92.         if (file != null && file.exists()) {  
    93.             entity.addPart("file"new FileBody(file));  
    94.         }  
    95.         post.setEntity(entity);  
    96.         HttpResponse response = client.execute(post);  
    97.         int stateCode = response.getStatusLine().getStatusCode();  
    98.         StringBuffer sb = new StringBuffer();  
    99.         if (stateCode == HttpStatus.SC_OK) {  
    100.             HttpEntity result = response.getEntity();  
    101.             if (result != null) {  
    102.                 InputStream is = result.getContent();  
    103.                 BufferedReader br = new BufferedReader(  
    104.                         new InputStreamReader(is));  
    105.                 String tempLine;  
    106.                 while ((tempLine = br.readLine()) != null) {  
    107.                     sb.append(tempLine);  
    108.                 }  
    109.             }  
    110.         }  
    111.         post.abort();  
    112.         return sb.toString();  
    113.     }  
    114.   
    115.     private String doGet(String url) {  
    116.         StringBuilder sb = new StringBuilder();  
    117.         try {  
    118.             HttpGet get = new HttpGet(url);  
    119.             // HttpPost post = new HttpPost(url);  
    120.   
    121.             HttpClient client = new DefaultHttpClient();  
    122.             HttpResponse response = client.execute(get);  
    123.             StatusLine state = response.getStatusLine();  
    124.             if (state.getStatusCode() == HttpStatus.SC_OK) {  
    125.                 HttpEntity eneity = response.getEntity();  
    126.                 BufferedReader br = new BufferedReader(new InputStreamReader(  
    127.                         eneity.getContent()));  
    128.                 String content;  
    129.                 while ((content = br.readLine()) != null) {  
    130.                     sb.append(content);  
    131.                 }  
    132.             }  
    133.             get.abort();  
    134.         } catch (Exception e) {  
    135.             e.printStackTrace();  
    136.             return sb.toString();  
    137.         }  
    138.         return sb.toString();  
    139.     }  
    140. }  

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

    [html] view plaincopy
    1. <uses-permission android:name="android.permission.CAMERA" />  
    2. <uses-permission android:name="android.permission.INTERNET" />  
    3. <uses-permission android:name="android.permission.VIBRATE" />  
    4. <uses-permission android:name="android.permission.INTERNET" />  
    5. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
    6. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  


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

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


  • 相关阅读:
    centos6.8添加crontab定时启动任务
    centos7用户最大进程限制导致的问题排查
    centos ftp 服务器搭建
    centos6.8的坑
    华为云centos服务器挂载云硬盘
    华为云windows开启特定端口
    华为云centos上命令
    排查机器服务无法使用步骤
    高(0.10.X以上版本)低(0.10.X以下版本)版本kafka如何共存
    PHP array_column重新构建二维数组
  • 原文地址:https://www.cnblogs.com/walccott/p/4957594.html
Copyright © 2011-2022 走看看