Android更换头像功能实现

现在不管什么APP都有个头像,如果你看见没有头像的APP就会感觉非常奇怪,以前头像都是方的,后来就变成圆的,我估计在过个几年就得来个五角星形状的头像,下面我把更换头像的代码写来:

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <ImageView  
  8.         android:id="@+id/iv_head"  
  9.         android:layout_width="200dip"  
  10.         android:layout_height="200dip"  
  11.         android:layout_alignParentTop="true"  
  12.         android:layout_centerHorizontal="true"  
  13.         android:layout_marginTop="210dip"  
  14.         android:src="@drawable/ic_launcher" />  
  15.   
  16.     <Button  
  17.         android:id="@+id/btn_takephoto"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content"  
  20.         android:layout_alignParentLeft="true"  
  21.         android:layout_alignParentTop="true"  
  22.         android:text="拍照" />  
  23.   
  24.     <Button  
  25.         android:id="@+id/btn_photos"  
  26.         android:layout_width="wrap_content"  
  27.         android:layout_height="wrap_content"  
  28.         android:layout_alignParentRight="true"  
  29.         android:layout_alignParentTop="true"  
  30.         android:text="从相册取" />  
  31.   
  32. </RelativeLayout>  

 

首先我定义了一个非常简单的XML布局,里面两个Button,一个ImageView用来显示头像:

下面我来看看MainActivity代码:

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.example.changhead;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8.   
  9. import android.net.Uri;  
  10. import android.os.Bundle;  
  11. import android.os.Environment;  
  12. import android.provider.MediaStore;  
  13. import android.annotation.SuppressLint;  
  14. import android.app.Activity;  
  15. import android.content.Intent;  
  16. import android.graphics.Bitmap;  
  17. import android.graphics.BitmapFactory;  
  18. import android.graphics.drawable.BitmapDrawable;  
  19. import android.graphics.drawable.Drawable;  
  20. import android.view.View;  
  21. import android.view.View.OnClickListener;  
  22. import android.widget.Button;  
  23. import android.widget.ImageView;  
  24.   
  25. @SuppressLint("SdCardPath")  
  26. public class MainActivity extends Activity implements OnClickListener {  
  27.     private ImageView ivHead;//头像显示  
  28.     private Button btnTakephoto;//拍照  
  29.     private Button btnPhotos;//相册  
  30.     private Bitmap head;//头像Bitmap  
  31.     private static String path="/sdcard/myHead/";//sd路径  
  32.   
  33.     @Override  
  34.     protected void onCreate(Bundle savedInstanceState) {  
  35.         super.onCreate(savedInstanceState);  
  36.         setContentView(R.layout.activity_main);  
  37.         initView();  
  38.     }  
  39.   
  40.     private void initView() {  
  41.         //初始化控件  
  42.         btnPhotos = (Button) findViewById(R.id.btn_photos);  
  43.         btnTakephoto = (Button) findViewById(R.id.btn_takephoto);  
  44.         btnPhotos.setOnClickListener(this);  
  45.         btnTakephoto.setOnClickListener(this);  
  46.         ivHead = (ImageView) findViewById(R.id.iv_head);  
  47.         Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");//从Sd中找头像,转换成Bitmap  
  48.         if(bt!=null){  
  49.             @SuppressWarnings("deprecation")  
  50.             Drawable drawable = new BitmapDrawable(bt);//转换成drawable  
  51.             ivHead.setImageDrawable(drawable);  
  52.         }else{  
  53.             /** 
  54.              *  如果SD里面没有则需要从服务器取头像,取回来的头像再保存在SD中 
  55.              *  
  56.              */  
  57.         }  
  58.           
  59.           
  60.       
  61.     }  
  62.   
  63.     @Override  
  64.     public void onClick(View v) {  
  65.         switch (v.getId()) {  
  66.         case R.id.btn_photos://从相册里面取照片  
  67.             Intent intent1 = new Intent(Intent.ACTION_PICK, null);  
  68.             intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");  
  69.             startActivityForResult(intent1, 1);  
  70.             break;  
  71.         case R.id.btn_takephoto://调用相机拍照  
  72.             Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  73.             intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),  
  74.                             "head.jpg")));  
  75.             startActivityForResult(intent2, 2);//采用ForResult打开  
  76.             break;  
  77.         default:  
  78.             break;  
  79.         }  
  80.     }  
  81.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  82.         switch (requestCode) {  
  83.         case 1:  
  84.             if (resultCode == RESULT_OK) {  
  85.                 cropPhoto(data.getData());//裁剪图片  
  86.             }  
  87.   
  88.             break;  
  89.         case 2:  
  90.             if (resultCode == RESULT_OK) {  
  91.                 File temp = new File(Environment.getExternalStorageDirectory()  
  92.                         + "/head.jpg");  
  93.                 cropPhoto(Uri.fromFile(temp));//裁剪图片  
  94.             }  
  95.   
  96.             break;  
  97.         case 3:  
  98.             if (data != null) {  
  99.                 Bundle extras = data.getExtras();  
  100.                 head = extras.getParcelable("data");  
  101.                 if(head!=null){  
  102.                     /**  
  103.                      * 上传服务器代码  
  104.                      */  
  105.                     setPicToView(head);//保存在SD卡中  
  106.                     ivHead.setImageBitmap(head);//用ImageView显示出来  
  107.                 }  
  108.             }  
  109.             break;  
  110.         default:  
  111.             break;  
  112.   
  113.         }  
  114.         super.onActivityResult(requestCode, resultCode, data);  
  115.     };  
  116.     /** 
  117.      * 调用系统的裁剪 
  118.      * @param uri 
  119.      */  
  120.     public void cropPhoto(Uri uri) {  
  121.         Intent intent = new Intent("com.android.camera.action.CROP");  
  122.         intent.setDataAndType(uri, "image/*");  
  123.         intent.putExtra("crop", "true");  
  124.          // aspectX aspectY 是宽高的比例  
  125.         intent.putExtra("aspectX", 1);  
  126.         intent.putExtra("aspectY", 1);  
  127.         // outputX outputY 是裁剪图片宽高  
  128.         intent.putExtra("outputX", 150);  
  129.         intent.putExtra("outputY", 150);  
  130.         intent.putExtra("return-data", true);  
  131.         startActivityForResult(intent, 3);  
  132.     }  
  133.     private void setPicToView(Bitmap mBitmap) {  
  134.          String sdStatus = Environment.getExternalStorageState();    
  135.         if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用    
  136.                return;    
  137.            }    
  138.         FileOutputStream b = null;  
  139.         File file = new File(path);  
  140.         file.mkdirs();// 创建文件夹  
  141.         String fileName =path + "head.jpg";//图片名字  
  142.         try {  
  143.             b = new FileOutputStream(fileName);  
  144.             mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件  
  145.               
  146.         } catch (FileNotFoundException e) {  
  147.             e.printStackTrace();  
  148.         } finally {  
  149.             try {  
  150.                 //关闭流  
  151.                 b.flush();  
  152.                 b.close();  
  153.             } catch (IOException e) {  
  154.                 e.printStackTrace();  
  155.             }  
  156.   
  157.         }  
  158. }  
  159. }  

上面的注释已经很详细了,就这些

 

对了不要忘记加权限:

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <uses-permission android:name="android.permission.CAMERA"/>  
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  3. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>    


源码下载

posted @ 2016-12-30 11:16  天涯海角路  阅读(365)  评论(0)    收藏  举报