android实现头像更改并保存(调用系统相册,系统相机)

Posted 谜语+

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android实现头像更改并保存(调用系统相册,系统相机)相关的知识,希望对你有一定的参考价值。

先给大家展示一下效果图:

 

 

点击头像会弹出对话框,提示选择路径相机,相册

代码如下:

private ImageView iv;
iv=findViewById(R.id.imagetouxiang);


iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("获取图片方式");
                builder.setItems(new String[]{"拍照", "相册"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case 0:

                                break;
                            case 1:

                                break;
                        }
                    }
                });
                builder.create().show();
            }
        });

(当中的点击事件我没写,最后会有补充)

 

接着是布局页面

(这个我就不写我给的图片中的布局了,给大家只放个图片,用来完成这个案例即可)

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

    <ImageView
        android:id="@+id/imagetouxiang"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        />
    

</LinearLayout>

 

还有个重要的是权限,在清单文件(AndroidManifest.xml)中写

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />

<uses-permission android:name="android.permission.INTERNET" />

 

重要的工具类BitmapUtils

package com.example.ablumtest;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;

public class BitmapUtils {
    public static Bitmap circleBitmap(Bitmap source){
        //默认只对宽进行处理
        int width=source.getWidth();
        Bitmap bitmap=Bitmap.createBitmap(width,width,Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(bitmap);
        Paint paint=new Paint();    //设置抗锯齿
        paint.setAntiAlias(true);
        canvas.drawCircle(width/2,width/2,width/2,paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source,0,0,paint);
        return bitmap;
    }
    /**   * 该方法用于图片压缩处理,注意width、height参数的类型必须是float   * */
    public static Bitmap zoom(Bitmap source,float width,float height){
        Matrix matrix=new Matrix();    //图片进行压缩处理
         matrix.postScale(width/source.getWidth(),height/source.getHeight());
         Bitmap bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
         return bitmap;
    }
}

 

还有一个onActivityResult,用来activity做出回应(这里说明一下,我上边的对话框,每一个case都有他对应的事件)

下边我给大家暂时在这写一下

case 0:
    Intent intent2=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent2,200);
    break;
case 1:
    Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent,100);
    break;        

 

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==100&&resultCode==RESULT_OK&&data!=null){//系统相册
            Uri imageData = data.getData();
            String path= getPath(imageData);
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            Bitmap bitmap1 = BitmapUtils.zoom(bitmap, iv.getWidth(), iv.getHeight());
            Bitmap bitmap2 = BitmapUtils.circleBitmap(bitmap1);
            //加载显示
            iv.setImageBitmap(bitmap2);
            //bitmap图片上传到服务器......
            //bitmap图片保存到本地
            saveImage(bitmap2);
        }else if(requestCode==200&&resultCode==RESULT_OK&&data!=null){//系统相机
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            BitmapUtils.zoom(bitmap,iv.getWidth(),iv.getHeight());
            bitmap=BitmapUtils.circleBitmap(bitmap);
            //加载显示
            iv.setImageBitmap(bitmap);
            //bitmap图片上传到服务器......
            //bitmap图片保存到本地
            saveImage(bitmap);
        }
    }

 

下面给大家贴上完整代码:

package com.example.ablumtest;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

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

public class AlbumfirstActivity extends AppCompatActivity {

    private ImageView iv;//要设置的头像

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

        iv=(ImageView) findViewById(R.id.imagetouxiang);

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AblumfirstActivity.this);
                builder.setTitle("获取图片方式");
                builder.setItems(new String[]{"拍照", "相册"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case 0:
                                Intent intent2=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(intent2,200);
                                break;
                            case 1:
                                Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(intent,100);
                                break;
                        }
                    }
                });
                builder.create().show();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==100&&resultCode==RESULT_OK&&data!=null){//系统相册
            Uri imageData = data.getData();
            String path= getPath(imageData);
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            Bitmap bitmap1 = BitmapUtils.zoom(bitmap, iv.getWidth(), iv.getHeight());
            Bitmap bitmap2 = BitmapUtils.circleBitmap(bitmap1);
            //加载显示
            iv.setImageBitmap(bitmap2);
            //bitmap图片上传到服务器......
            //bitmap图片保存到本地
            saveImage(bitmap2);
        }else if(requestCode==200&&resultCode==RESULT_OK&&data!=null){//系统相机
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            BitmapUtils.zoom(bitmap,iv.getWidth(),iv.getHeight());
            bitmap=BitmapUtils.circleBitmap(bitmap);
            //加载显示
            iv.setImageBitmap(bitmap);
            //bitmap图片上传到服务器......
            //bitmap图片保存到本地
            saveImage(bitmap);
        }
    }


    private void saveImage(Bitmap bitmap) {
        File filesDir;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//判断sd卡是否挂载
            //路径1:storage/sdcard/Android/data/包名/files
            filesDir = this.getExternalFilesDir("");
        }else{//手机内部存储
            //路径:data/data/包名/files
            filesDir = this.getFilesDir();
        }
        FileOutputStream fos = null;
        try {
            File file = new File(filesDir,"icon.png");
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100,fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //如果本地有,就不需要再去联网去请求
    private boolean readImage() {
        File filesDir;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//判断sd卡是否挂载
            //路径1:storage/sdcard/Android/data/包名/files
            filesDir = getExternalFilesDir("");
        }else{//手机内部存储
            //路径:data/data/包名/files
            filesDir = getFilesDir();
        }
        File file = new File(filesDir,"icon.png");
        if(file.exists()){
            //存储--->内存
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            iv.setImageBitmap(bitmap);
            return true;
        }
        return false;
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private String getPath(Uri uri) {
        int sdkVersion = Build.VERSION.SDK_INT;
        //高于4.4.2的版本
        if (sdkVersion >= 19) {
            Log.e("TAG", "uri auth: " + uri.getAuthority());
            if (isExternalStorageDocument(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(this, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(this, contentUri, selection, selectionArgs);
            } else if (isMedia(uri)) {
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor actualimagecursor = this.managedQuery(uri, proj, null, null, null);
                int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                return actualimagecursor.getString(actual_image_column_index);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(this, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }
    /**
     * uri路径查询字段
     *
     * @param context
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
    private boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
    public static boolean isMedia(Uri uri) {
        return "media".equals(uri.getAuthority());
    }
    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
    /**
     * 判断本地是否有该图片,没有则去联网请求
     * */
    @Override
    protected void onResume() {
        super.onResume();
        if(readImage()){
            return;
        }
    }



}

 

以上是关于android实现头像更改并保存(调用系统相册,系统相机)的主要内容,如果未能解决你的问题,请参考以下文章

H5调用手机相机和相册,并且将图片转化为base64的格式

调用系统相册上传头像到服务器

调用系统相册上传头像到服务器

Android中通过访问本地相册或者相机设置用户头像

Android WebView 调用系统拍照和相册

安卓开发——拍照裁剪并保存为头像报错:裁剪图片无法保存的