首页 > 代码库 > 即拿即用-选择头像,可以选择相册,拍照,查看大图,保存到本地

即拿即用-选择头像,可以选择相册,拍照,查看大图,保存到本地

技术分享

如图所示:

  • 显示图片用的是Glide

  • 选择图片用的是GalleryFinal

  • 查看大图用的是PhotView

  • 圆形图片用的是SelectableRoundedImageView

GitHub地址:https://github.com/mocn26169/Avatar

核心代码:

点击选择图片

  @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.avatar:
                if (!TextUtils.isEmpty(url)) {
                    new ActionSheetDialog(GalleryFinalActivity.this)
                            .builder()
                            .setCancelable(true)
                            .setCanceledOnTouchOutside(true)
                            .addSheetItem("相册", SheetItemColor.Blue,
                                    new OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            // GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, mOnHanlderResultCallback);
                                            //带配置
                                            functionConfig = new FunctionConfig.Builder()
                                                    .setEnableCamera(false)
                                                    .setEnableEdit(false)
                                                    .setEnableCrop(true)
                                                    .setEnableRotate(true)
                                                    .setCropSquare(true)
                                                    .setEnablePreview(true)
                                                    .build();
                                            GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, functionConfig, mOnHanlderResultCallback);
                                        }
                                    })
                            .addSheetItem("拍照", SheetItemColor.Blue,
                                    new OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mOnHanlderResultCallback);
                                        }
                                    }
                            )
                            .addSheetItem("查看大图", SheetItemColor.Blue,
                                    new OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            Intent intent = new Intent(GalleryFinalActivity.this, BrowsePictureActivity.class);
                                            intent.putExtra("url", url);
                                            startActivity(intent);
                                        }
                                    }
                            )
                            .show();
                } else {
                    new ActionSheetDialog(GalleryFinalActivity.this)
                            .builder()
                            .setCancelable(true)
                            .setCanceledOnTouchOutside(true)
                            .addSheetItem("相册", SheetItemColor.Blue,
                                    new OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {

                                        }
                                    })
                            .addSheetItem("拍照", SheetItemColor.Blue,
                                    new OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mOnHanlderResultCallback);
                                        }
                                    }
                            )
                            .show();
                }

                break;

            default:
                break;
        }
    }

回调成功显示图片

   private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (resultList != null && resultList.size() > 0) {
                url = resultList.get(0).getPhotoPath();
                Log.e("MainActivity", "url=" + url);

                Glide
                        .with(GalleryFinalActivity.this)
                        .load("file://" + url)
                        .asBitmap()
//                        .load("https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=2561733620,2304282159&fm=85&s=E71450848ABEFCCE643AA8800300308C")
//                        .centerCrop()
                        .placeholder(R.mipmap.default_placeholder)
//                        .crossFade()
                        .into(avatar);
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(GalleryFinalActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
        }
    };
}

保存图片到本地

  view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    new ActionSheetDialog(BrowsePictureActivity.this)
                            .builder()
                            .setCancelable(true)
                            .setCanceledOnTouchOutside(true)
                            .addSheetItem("保存到手机", SheetItemColor.Blue,
                                    new OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            onDownLoad(url);
                                        }
                                    })

                            .show();
                    return true;
                }
            });
/**
     * 启动图片下载线程
     */
    private void onDownLoad(String url) {
        ProgressUtils.show(BrowsePictureActivity.this, null, "正在保存,请耐心等候......");
        DownLoadImageService service = new DownLoadImageService(getApplicationContext(),
                url,
                new ImageDownLoadCallBack() {

                    @Override
                    public void onDownLoadSuccess(File file, String url) {

                    }

                    @Override
                    public void onDownLoadSuccess(Bitmap bitmap, String url) {
                        // 在这里执行图片保存方法
                        Message message = new Message();
                        message.what = MSG_VISIBLE;
                        message.obj = url;
                        downLoadHandler.sendMessage(message);
                    }

                    @Override
                    public void onDownLoadFailed() {
                        // 图片保存失败
                        Message message = new Message();
                        message.what = MSG_ERROR;
                        downLoadHandler.sendMessage(message);
                    }
                });

        //启动图片下载线程
        new Thread(service).start();
    }
package com.bourne.avatar;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;

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

/**
 * 图片下载
 */
public class DownLoadImageService implements Runnable {
    private String url;
    private Context context;
    private ImageDownLoadCallBack callBack;
    private File currentFile;

    public DownLoadImageService(Context context, String url, ImageDownLoadCallBack callBack) {
        this.url = url;
        this.callBack = callBack;
        this.context = context;
    }

    @Override
    public void run() {
        File file = null;
        Bitmap bitmap = null;
        String savePicturePosition = "";
        try {
//            file = Glide.with(context)
//                    .load(url)
//                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
//                    .get();
            bitmap = Glide.with(context)
                    .load(url)
                    .asBitmap()
                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();
            if (bitmap != null) {
                // 在这里执行图片保存方法
                savePicturePosition = saveImageToGallery(context, bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            if (file != null) {
//                callBack.onDownLoadSuccess(file);
//            } else {
//                callBack.onDownLoadFailed();
//            }
            if (bitmap != null && currentFile.exists()) {
                callBack.onDownLoadSuccess(bitmap, savePicturePosition);
            } else {
                callBack.onDownLoadFailed();
            }
        }
    }

    public String saveImageToGallery(Context context, Bitmap bmp) {
        String savePicturePosition = null;
        // 首先保存图片
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        String dirName = "Avatar";
        File appDir = new File(file, dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }

        String fileName = System.currentTimeMillis() + ".jpg";
        currentFile = new File(appDir, fileName);
        savePicturePosition = currentFile.getAbsolutePath();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    currentFile.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));

        return savePicturePosition;
    }
}
package com.bourne.avatar;

import android.graphics.Bitmap;
import java.io.File;

public interface ImageDownLoadCallBack {
    void onDownLoadSuccess(File file,String url);
    void onDownLoadSuccess(Bitmap bitmap,String url);

    void onDownLoadFailed();
}

一个避免内存泄露的Handler,具体可见《 Android内存优化方案和内存泄露检测分析方法》

private static class DownLoadHandler extends Handler {

        private WeakReference<BrowsePictureActivity> activityWeakReference;

        public DownLoadHandler(BrowsePictureActivity activity) {
            this.activityWeakReference = new WeakReference<BrowsePictureActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            ProgressUtils.dissmiss();

            BrowsePictureActivity activity = activityWeakReference.get();
            if (activity != null) {
                if (msg.what == MSG_VISIBLE) {
                    new AlertDialog(activity).builder()
                            .setMsg("图片保存成功,路径为" + msg.obj)
                            .setNegativeButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            }).show();

//                    Toast.makeText(activity, "文件已保存在" + msg.obj, Toast.LENGTH_LONG).show();
                } else if (msg.what == MSG_ERROR) {
                    new AlertDialog(activity).builder()
                            .setMsg("图片保存失败" + msg.obj)
                            .setNegativeButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            }).show();
//                    Toast.makeText(activity, "文件保存失败", Toast.LENGTH_LONG).show();
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        downLoadHandler.removeCallbacksAndMessages(null);
    }

参考

  • https://github.com/pengjianbo/GalleryFinal GalleryFinal

  • https://github.com/bumptech/glide Glide

  • https://github.com/chrisbanes/PhotoView PhotView

  • https://github.com/pungrue26/SelectableRoundedImageView SelectableRoundedImageView

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

    即拿即用-选择头像,可以选择相册,拍照,查看大图,保存到本地