android-拍照/选择相册获取图片并编辑

效果图:

实现步骤:

1.添加依赖:

    //photoview
    implementation 'com.github.chrisbanes.photoview:library:1.2.4'
    //使用Crop裁剪图片
    implementation('com.yalantis:ucrop:2.2.0') {
        exclude group: 'com.android.support'
        exclude group: 'com.squareup.okio'
        exclude group: 'com.squareup.okhttp3'
    }

2.注册:注意此处是直接添加而不是新建Activity修改

3.上代码:

import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
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.support.annotation.RequiresApi;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.yalantis.ucrop.UCrop;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ds.com.dingshi.R;
import ds.com.dingshi.base.BaseActivity;

//我的头像     查看,更换头像操作
public class MineHeaderHandleActivity extends BaseActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.titleTv1)
    TextView titleTv1;
    @BindView(R.id.more_iv)
    ImageView moreIv;
    @BindView(R.id.pv)
    uk.co.senab.photoview.PhotoView pv;
    private String headerUrl;
    private File file;

    private static final int CAMERA = 502;
    private static final int PHOTO = 501;
    private Uri imageUri;

    private String filePath;//文件path
    private String TAG = "MineHeaderHandleActivity";
    private Uri destinationUri;

    @Override
    public int getLayoutId() {
        return R.layout.activity_mine_header_handle;
    }

    @Override
    public void initView() {
        headerUrl = getIntent().getStringExtra("headerUrl");
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(R.drawable.icon_error);//图片加载出来前,显示的图片
        requestOptions.error(R.drawable.icon_error);//图片加载失败后,显示的图片
        Glide.with( MineHeaderHandleActivity.this)//content是上下文
                .load("http://img1.mukewang.com/56aa17e800018e6101000100-100-100.jpg")//图片地址
                .apply(requestOptions)
                .into(pv);//ImageView控件
        /*Glide.with(MineHeaderHandleActivity.this).load("http://img1.mukewang.com/56aa17e800018e6101000100-100-100.jpg")
                .placeholder(R.drawable.icon_error).crossFade().centerCrop()
                .into(pv);*/
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.back, R.id.more_iv, R.id.pv})
    public void onClick(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.more_iv:
                String[] items = new String[]{"图库","相机"};
                new AlertDialog.Builder(this)
                        .setTitle("选择来源")
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which){
                                    case 0://图库
                                        Intent intent = new Intent();
                                        intent.setType("image/*");
                                        intent.setAction(Intent.ACTION_PICK);//打开图库
                                        //REQUEST_PICTURE_CHOOSE表示请求参数,是个常量
                                        startActivityForResult(intent, PHOTO);
                                        break;
                                    case 1://相机
                                        File mPictureFile = new File(getExternalCacheDir(), "_" + System.currentTimeMillis() + ".jpg");
                                        imageUri = Uri.fromFile(mPictureFile);
                                        // 启动拍照,并保存到临时文件
                                        Intent mIntent = new Intent();
                                        mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                                        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPictureFile));
                                        mIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                                        startActivityForResult(mIntent, CAMERA);
                                        break;
                                }
                            }
                        })
                        .setCancelable(true)
                        .show();
                break;
            case R.id.pv:
                //单纯的点击图片全屏展示
//                initImageView("");
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //通过回调获取返回结果
        switch (requestCode) {
            case PHOTO:
                if (resultCode == RESULT_OK) {
                    if (resultCode == RESULT_OK) {
                        Uri sourceUri = data.getData();
                        startUCrop(sourceUri);
                    } else {
                        Toast.makeText(this, "选图失败!", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case CAMERA:
                if (resultCode == RESULT_OK) {
                    startUCrop(imageUri);
                }
                break;
            //裁剪后的效果
            //裁剪后的效果
            case UCrop.REQUEST_CROP:
                if (resultCode == RESULT_OK) {
                    Uri resultUri = UCrop.getOutput(data);
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(resultUri));
                        pv.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            //错误裁剪的结果
            case UCrop.RESULT_ERROR:
                if (resultCode == RESULT_OK) {
                    final Throwable cropError = UCrop.getError(data);
                    handleCropError(cropError);
                }
                break;
        }
    }
    /**
     * 裁剪图片
     *
     * @param sourceUri
     */
    private void startUCrop(Uri sourceUri) {
        UCrop.Options options = new UCrop.Options();
        //裁剪后图片保存在文件夹中
        Uri destinationUri = Uri.fromFile(new File(getExternalCacheDir(), "uCrop.jpg"));
        UCrop uCrop = UCrop.of(sourceUri, destinationUri);//第一个参数是裁剪前的uri,第二个参数是裁剪后的uri
        uCrop.withAspectRatio(1, 1);//设置裁剪框的宽高比例
        //下面参数分别是缩放,旋转,裁剪框的比例
        options.setAllowedGestures(com.yalantis.ucrop.UCropActivity.ALL, com.yalantis.ucrop.UCropActivity.NONE, com.yalantis.ucrop.UCropActivity.ALL);
        options.setToolbarTitle("移动和缩放");//设置标题栏文字
        options.setCropGridStrokeWidth(2);//设置裁剪网格线的宽度(我这网格设置不显示,所以没效果)
        //options.setCropFrameStrokeWidth(1);//设置裁剪框的宽度
        options.setMaxScaleMultiplier(3);//设置最大缩放比例
        //options.setHideBottomControls(true);//隐藏下边控制栏
        options.setShowCropGrid(true);  //设置是否显示裁剪网格
        //options.setOvalDimmedLayer(true);//设置是否为圆形裁剪框
        options.setShowCropFrame(true); //设置是否显示裁剪边框(true为方形边框)
        options.setToolbarWidgetColor(Color.parseColor("#ffffff"));//标题字的颜色以及按钮颜色
        options.setDimmedLayerColor(Color.parseColor("#AA000000"));//设置裁剪外颜色
        options.setToolbarColor(Color.parseColor("#000000")); // 设置标题栏颜色
        options.setStatusBarColor(Color.parseColor("#000000"));//设置状态栏颜色
        options.setCropGridColor(Color.parseColor("#ffffff"));//设置裁剪网格的颜色
        options.setCropFrameColor(Color.parseColor("#ffffff"));//设置裁剪框的颜色
        uCrop.withOptions(options);
        /*//裁剪后保存到文件中
        Uri destinationUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/myxmpp/" + "test1.jpg"));
        UCrop uCrop = UCrop.of(sourceUri, destinationUri);
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.orange2));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.orange2));
        //是否能调整裁剪框
        options.setFreeStyleCropEnabled(true);
        options.setToolbarWidgetColor(Color.parseColor("#ffffff"));//标题字的颜色以及按钮颜色
        options.setDimmedLayerColor(Color.parseColor("#AA000000"));//设置裁剪外颜色
        options.setToolbarColor(Color.parseColor("#000000")); // 设置标题栏颜色
        options.setStatusBarColor(Color.parseColor("#000000"));//设置状态栏颜色
        options.setCropGridColor(Color.parseColor("#ffffff"));//设置裁剪网格的颜色
        options.setCropFrameColor(Color.parseColor("#ffffff"));//设置裁剪框的颜色
        //options.setShowCropFrame(false); //设置是否显示裁剪边框(true为方形边框)
        uCrop.withOptions(options);*/
        uCrop.start(this);
    }


    //处理剪切失败的返回值
    private void handleCropError(Throwable cropError) {
        deleteTempPhotoFile();
        if (cropError != null) {
            Toast.makeText(MineHeaderHandleActivity.this, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(MineHeaderHandleActivity.this, "无法剪切选择图片", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 删除拍照临时文件
     */
    private void deleteTempPhotoFile() {
        File tempFile = new File(Environment.getExternalStorageDirectory() + File.separator + "output_iamge.jpg");
        if (tempFile.exists() && tempFile.isFile()) {
            tempFile.delete();
        }
    }
    public File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 2000) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(),filename+".jpg");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
//                BAFLogger.e(TAG,e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
//            BAFLogger.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }
    public void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps==null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }
    //点击图片全屏预览,缩放预览,再次点击关闭
    /*private void initImageView(String url) {
        final WindowManager windowManager = getWindowManager();
        final RelativeLayout relativeLayout = new RelativeLayout(MineHeaderHandleActivity.this);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        getScreenWidthAndHeight();
        layoutParams.width = mScreenWidth;
        layoutParams.height = mScreenHeight;
        //FLAG_LAYOUT_IN_SCREEN
        layoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        layoutParams.format = 2;//让背景透明,放大过程可以看到当前界面
        layoutParams.verticalMargin = 0;
        windowManager.addView(relativeLayout,layoutParams);

        final PhotoView animationIV = new PhotoView(MineHeaderHandleActivity.this);
        animationIV.setScaleType(ImageView.ScaleType.FIT_CENTER);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        relativeLayout.addView(animationIV,params);
        relativeLayout.setFocusableInTouchMode(true);
//        Picasso.with(SystemBugDBDetailActivity.this).load(url).into(animationIV);

        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(R.drawable.icon_error);//图片加载出来前,显示的图片
        requestOptions.error(R.drawable.icon_error);//图片加载失败后,显示的图片
        Glide.with(MineHeaderHandleActivity.this)//content是上下文
                .load(url)//图片地址
                .apply(requestOptions)
                .into(animationIV);//ImageView控件

        animationIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                windowManager.removeView(relativeLayout);
            }
        });
        animationIV.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
                windowManager.removeView(relativeLayout);
//                finish();
            }
        });
        relativeLayout.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (null != windowManager && null != relativeLayout) {
                        windowManager.removeView(relativeLayout);
                    }
                    return true;
                }
                return false;
            }
        });
    }*/
    /**
     * 获取当前屏幕宽高
     */
    /**
     * 屏幕的宽高
     */
    protected int mScreenWidth;
    protected int mScreenHeight;
    public void getScreenWidthAndHeight() {
        //获取当前屏幕宽高
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;
        mScreenHeight = metric.heightPixels;
    }
}

 

你可能感兴趣的:(安卓)