1. 程式人生 > >Android 頭像上傳 相機+相簿 繪製圓形頭像

Android 頭像上傳 相機+相簿 繪製圓形頭像

老話常談,在開始之前來幾張圖,看看效果:

主介面:



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main" tools:context=".MainActivity">

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

        <com.ynu.photo_upload.RoundImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:id="@+id/imageView"
            android:background="@android:color/transparent"
            android:layout_marginBottom="15dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center"
            android:layout_marginBottom="15dp">

            <Button
                android:layout_width="100dp"
                android:layout_height="30dp"
                android:id="@+id/Camera"
                android:background="@drawable/tabtop1"
                android:text="拍照"
                android:onClick="submit_camera"
                android:layout_marginRight="35dp"/>

            <Button
                android:layout_width="100dp"
                android:layout_height="30dp"
                android:id="@+id/gallery"
                android:background="@drawable/tabtop1"
                android:onClick="submit_gallery"
                android:text="相簿"/>

        </LinearLayout>

    </LinearLayout>


</LinearLayout><strong>
</strong>

Tabtop1.xml   bg樣式
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <stroke
        android:width="1dp"
        android:color="#585858"/>

    <corners
        android:radius="25dp"/>

</shape>

RoundImageView.java 自定義圓形繪製

package com.ynu.photo_upload;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by 江樹金 on 2016/4/12.
 */
public class RoundImageView extends ImageView { //重寫imageView設定為圓形

    public RoundImageView(Context context) {
        super(context);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }

        Bitmap b =  ((BitmapDrawable)drawable).getBitmap();

        if(null == b)
        {
            return;
        }

        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();


        Bitmap roundBitmap =  getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0,0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;
        if(bmp.getWidth() != radius || bmp.getHeight() != radius)
            sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
        else
            sbmp = bmp;
        Bitmap output = Bitmap.createBitmap(sbmp.getWidth(),
                sbmp.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xffa19774;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(sbmp.getWidth() / 2+0.7f, sbmp.getHeight() / 2+0.7f,
                sbmp.getWidth() / 2+0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}


MainActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    private static int Camera_Request_Code=1;
    private static int Gallery_Request_Code=2;
    private static int Crop_Ruquest_Code=3;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        imageView= (RoundImageView) findViewById(R.id.imageView);
        imageView.setImageResource(R.drawable.non_lanuch);
    }

    public void submit_camera(View v){//相機點選事件
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,Camera_Request_Code);
    }

    public void submit_gallery(View v){//相簿點選事件
        Intent intent1=new Intent(Intent.ACTION_GET_CONTENT);
        intent1.setType("image/*");
        startActivityForResult(intent1,Gallery_Request_Code);
    }

    /*SD卡目錄*/
    private Uri BitMap(Bitmap bitmap){
        File tmpDir=new File(Environment.getExternalStorageDirectory()+"/com.ynu.campusproject");    //儲存地址及命名
        if (!tmpDir.exists()){
            tmpDir.mkdir(); //生成目錄進行儲存
        }
        File img=new File(tmpDir.getAbsolutePath()+"upload.png");
        try {
            FileOutputStream fos=new FileOutputStream(img);
            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fos);  //參:壓縮的格式,圖片質量85,輸出流
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /*格式convert*/
    private Uri convertUri(Uri uri){//將從相簿中取出的轉換格式
        InputStream is=null;
        try {
            is=getContentResolver().openInputStream(uri);
            Bitmap bitmap= BitmapFactory.decodeStream(is);
            is.close();
            return BitMap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /*裁剪框大小設定*/
    private void imagecut(Uri uri){
        Intent intent=new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");//型別
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY",1);
        intent.putExtra("outputX",150);
        intent.putExtra("outputY",150);
        intent.putExtra("return-data",true);
        startActivityForResult(intent,Crop_Ruquest_Code);
    }

    //圓形Bitmap裁剪
    public Bitmap toRoundBitmap(Bitmap bitmap){//引用方法
        int width=bitmap.getWidth();
        int height=bitmap.getHeight();
        int r=0;
        //取最短邊做邊長
        if(width<height){
            r=width;
        }else{
            r=height;
        }
        //構建一個bitmap
        Bitmap backgroundBm=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
        //new一個Canvas,在backgroundBmp上畫圖
        Canvas canvas=new Canvas(backgroundBm);
        Paint p=new Paint();
        //設定邊緣光滑,去掉鋸齒
        p.setAntiAlias(true);
        RectF rect=new RectF(0, 0, r, r);
        //通過制定的rect畫一個圓角矩形,當圓角X軸方向的半徑等於Y軸方向的半徑時,
        //且都等於r/2時,畫出來的圓角矩形就是圓形
        canvas.drawRoundRect(rect, r/2, r/2, p);
        //設定當兩個圖形相交時的模式,SRC_IN為取SRC圖形相交的部分,多餘的將被去掉
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //canvas將bitmap畫在backgroundBmp上
        canvas.drawBitmap(bitmap, null, rect, p);
        return backgroundBm;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==Camera_Request_Code){//相機返回碼
            if (data==null){
                return;
            }else {
                Bundle extras=data.getExtras();
                if (extras!=null){
                    Bitmap bm=extras.getParcelable("data");
                    bm=toRoundBitmap(bm);
                    Uri uri=BitMap(bm);
                    imagecut(uri);  //呼叫該方法完成裁剪
                }
            }
        }else if (requestCode==Gallery_Request_Code){//相簿返回碼
            if (data==null){
                return;
            }
            Uri uri;
            uri=data.getData();
            Uri fileuri=convertUri(uri);
            imagecut(fileuri);  //...
        }
        else if (requestCode==Crop_Ruquest_Code){//裁剪返回碼
            if (data==null){
                return;
            }else {
                Bundle extras1=data.getExtras();
                Bitmap bm1=extras1.getParcelable("data");
                bm1=toRoundBitmap(bm1);
                imageView= (RoundImageView) findViewById(R.id.imageView);
                imageView.setImageBitmap(bm1);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {//無關項
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {//無關項
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

直接拿去就可以,不用謝哦~ 下一篇將要完成如何對檔案進行上傳處理,後臺服務使用雲平臺

Demo下載:http://download.csdn.net/detail/u013000304/9492516