跳转图库或相机返回照片(圆图片)

这里用到了权限PermissionGen-master第三方架构

package com.example.xiaohua;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.sqlite_database.Sqlite_Utils;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class Register extends AppCompatActivity implements View.OnClickListener {
    private ImageView registerUserImage;
    private EditText registerUserName;
    private EditText registerPassword;
    private EditText registerPassword2;
    private ImageView registerImageCode;
    private EditText registerVerificationCode;
    private Button registerButton;
    private String verificationCodetext;
   Handler handler=new Handler(){
       @Override
       public void handleMessage(Message msg) {
           switch (msg.what){
               case 110:
                   Toast.makeText(Register.this, "链接不到网络", Toast.LENGTH_SHORT).show();
                   break;
               case 119:
                   Bitmap birmap= (Bitmap) msg.obj;
                   registerImageCode.setImageBitmap(birmap);
                   mShow.dismiss();
                   break;
           }
       }
   };
    private ProgressDialog mShow;
    private Sqlite_Utils mSqlite_utils;
    private String mImagePath;
    private String mData;

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

    }

    private void init() {
        registerUserImage = (ImageView) findViewById(R.id.register_user_image);
        registerUserName = (EditText) findViewById(R.id.register_user_name);
        registerPassword = (EditText) findViewById(R.id.register_password);
        registerPassword2 = (EditText) findViewById(R.id.register_password2);
        registerImageCode = (ImageView) findViewById(R.id.register_image_code);
        registerVerificationCode = (EditText) findViewById(R.id.register_Verification_Code);
        registerButton = (Button) findViewById(R.id.register_button);
        registerUserImage.setOnClickListener(this);
//将上下文菜单绑定到指定的控件上   通过长按弹出
        registerForContextMenu(registerUserImage);
        registerImageCode.setOnClickListener(this);

        registerButton.setOnClickListener(this);
         mShow = ProgressDialog.show(this, "加载数据", "加载中....");
        mSqlite_utils = new Sqlite_Utils(this);
    }

    private void upImagecode() {
        new Thread() {
            @Override
            public void run() {
                try {
//                    20180724003110
                    SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateStr = dateformat.format(System.currentTimeMillis());
                    Log.e("tag", "run: "+dateStr);
                    URL url = new URL("https://route.showapi.com/26-4?border=&border_color=105,179,90" +
                            "&border_thickness=&image_height=&image_width=&noise_color" +
                            "=105,179,90&obscurificator_impl=&showapi_appid=71311" +
                            "&showapi_timestamp="+dateStr+"&textproducer_char_length=" +
                            "&textproducer_char_space=&textproducer_char_string=" +
                            "&textproducer_font_color=105,179,90&textproducer_font_names=" +
                            "&textproducer_font_size=&showapi_sign=678d17d2c5524ad88a7df7c487d549dc");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(3000);
                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode == 200) {
                        InputStream inputStream = urlConnection.getInputStream();
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        byte data[]=new byte[1024];
                        int lenth=0;
                        while ((lenth=inputStream.read(data))!=-1){
                            byteArrayOutputStream.write(data,0,lenth);
                            byteArrayOutputStream.flush();
                        }
                        inputStream.close();
                        byteArrayOutputStream.close();
                        String JSONtext = byteArrayOutputStream.toString();
                        JSONObject jsonObject = new JSONObject(JSONtext);
                        Log.e("tag", "run: " +JSONtext);
                        int ret_code = jsonObject.getInt("showapi_res_code");
                        if(ret_code==0){
                            JSONObject showapi_res_body = jsonObject.getJSONObject("showapi_res_body");
                            String img_path = showapi_res_body.getString("img_path");
                            verificationCodetext= showapi_res_body.getString("text");
                            URL url1 = new URL(img_path);
                            HttpURLConnection urlConnection1 = (HttpURLConnection) url1.openConnection();
                            urlConnection1.setRequestMethod("GET");
                            urlConnection1.setConnectTimeout(5000);
                            int responseCode1 = urlConnection1.getResponseCode();
                            if(responseCode1==200){
                                InputStream inputStream1 = urlConnection1.getInputStream();
                                Bitmap bitmap = BitmapFactory.decodeStream(inputStream1);
                                Message obtain = Message.obtain();
                                obtain.obj=bitmap;
                                obtain.what=119;
                                handler.sendMessage(obtain);

                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(110);
                }

            }
        }.start();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_user_image://头像



                break;
            case R.id.register_image_code://更换验证码
                upImagecode();
                break;
            case R.id.register_button://注册
                String name = registerUserName.getText().toString().trim();
                String pwd = registerPassword.getText().toString().trim();
                String pwd2 = registerPassword2.getText().toString().trim();
                String trim = registerVerificationCode.getText().toString().trim();
               if(TextUtils.isEmpty(verificationCodetext)){
                   Toast.makeText(this, "查看联网", Toast.LENGTH_SHORT).show();
               return;
               }
                if(trim.equals(verificationCodetext)){
                    if(pwd.length()>=8){
                        Toast.makeText(this, "输入密码长度不符合", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(name.length()>7||name.length()<=5){
                        Toast.makeText(this, "输入账户长度不符合", Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        if(pwd.equals(pwd2)){
                            boolean adddata = mSqlite_utils.adddata(name, pwd2,mImagePath);
                      if(adddata){
                          Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                          Intent intent = new Intent();
                          intent.putExtra("user",name);
                          intent.putExtra("pwd2",pwd);
                          setResult(119,intent);
                          finish();
                      }else{
                          Toast.makeText(this, "已有此账户", Toast.LENGTH_SHORT).show();
                      }
                        }else{
                            Toast.makeText(this, "确认密码不一致", Toast.LENGTH_SHORT).show();
                        }

                    }
             }else {
                    Toast.makeText(this, "输入验证码错误", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 0){
            Bundle extras = data.getExtras();
            Bitmap mImageBitmap = (Bitmap) extras.get("data");
            mData = data.getStringExtra("data");
            Drawable d = createRoundImageWithBorder(mImageBitmap);
            registerUserImage.setImageDrawable(d);
        }
        if(requestCode == 1){
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            if(data==null){
                Toast.makeText(this, "取消", Toast.LENGTH_SHORT).show();
                return;
            }
            Cursor cursor = getContentResolver().query(data.getData(),
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mImagePath = cursor.getString(columnIndex);
            Bitmap bitmap = BitmapFactory.decodeFile(mImagePath);
            Drawable d = createRoundImageWithBorder(bitmap);
            registerUserImage.setImageDrawable(d);

            cursor.close();
        }
    }
    private Drawable createRoundImageWithBorder(Bitmap bitmap){
        //原图宽度
        int bitmapWidth = bitmap.getWidth();
        //原图高度
        int bitmapHeight = bitmap.getHeight();
        //边框宽度 pixel
        int borderWidthHalf = 20;

        //转换为正方形后的宽高
        int bitmapSquareWidth = Math.min(bitmapWidth,bitmapHeight);

        //最终图像的宽高
        int newBitmapSquareWidth = bitmapSquareWidth+borderWidthHalf;

        Bitmap roundedBitmap = Bitmap.createBitmap(newBitmapSquareWidth,newBitmapSquareWidth,Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(roundedBitmap);
        int x = borderWidthHalf + bitmapSquareWidth - bitmapWidth;
        int y = borderWidthHalf + bitmapSquareWidth - bitmapHeight;

        //裁剪后图像,注意X,Y要除以2 来进行一个中心裁剪
        canvas.drawBitmap(bitmap, x/2, y/2, null);
        Paint borderPaint = new Paint();
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setStrokeWidth(borderWidthHalf);
        borderPaint.setColor(Color.WHITE);

        //添加边框
        canvas.drawCircle(canvas.getWidth()/2, canvas.getWidth()/2, newBitmapSquareWidth/2, borderPaint);

        RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(),roundedBitmap);
        roundedBitmapDrawable.setGravity(Gravity.CENTER);
        roundedBitmapDrawable.setCircular(true);
        return roundedBitmapDrawable;
    }
    @Override//创建上下文菜单
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        //群组号   ID   显示顺序  显示文字
//        menu.add(0,0,0,"拍照");
        menu.add(0,1,1,"图库");
    }

    @Override//监听上下文菜单
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case 0:
                PermissionGen.needPermission(this,200,new String[]{
                        Manifest.permission.CAMERA});
                break;
            case 1:
                PermissionGen.needPermission(this,300,new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE});
                break;
        }
        return super.onContextItemSelected(item);
    }

    @PermissionSuccess(requestCode = 200)
    private  void Camera(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 0);
    }
    @PermissionSuccess(requestCode = 300)
    private void SDcard(){
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, 1);
    }
    @PermissionFail(requestCode = 200)
    private void fall(){
        Toast.makeText(this, "未许可权限", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this,requestCode,permissions,grantResults);
    }
}

image.png

你可能感兴趣的:(跳转图库或相机返回照片(圆图片))