1. 程式人生 > >Android 使用者圓形影象的設定與上傳

Android 使用者圓形影象的設定與上傳

</pre>使用者圓形影象的設定與上傳,技術使用了框架imageloader jar包,可以進行圖片的載入,可以使用imageloader 也可以自己寫  圖片的選擇當時選擇了系統自帶的圖片管理器,圖片的剪下使用系統自帶的。直接貼出程式碼</p><p>1.<img src="https://img-blog.csdn.net/20161102143159959?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><img src="https://img-blog.csdn.net/20161102143307944?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><img src="https://img-blog.csdn.net/20161102143415764?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><img src="https://img-blog.csdn.net/20161102143532109?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></p><p></p><p><pre name="code" class="java">public class SettingUserImageActivity extends BaseActivity implements View.OnClickListener {
    private static final int ALBUM_REQUEST_CODE = 1;
    private static final int CAMERA_REQUEST_CODE = 2;
    private static final int CROP_REQUEST_CODE = 4;
    private static final String IMAGE_UNSPECIFIED = "image/*";
    private TitleBarView titleBarView;
    private ImageView iv_user_image;
    private Button btn_photo, btn_camer;

    private static final int REQUEST_CAMERA = 0;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.CAMERA};

    @Override
    public int getLayoutResourse() {
        return R.layout.activity_setting_user_image;
    }

    @Override
    public void init() {
        settTitle();
        initView();
        initViewAfter();
    }

    private void initViewAfter() {
        ImageLoader.getInstance().displayImage("file:///storage/emulated/0/chaoyang/" + MyApplication.username + ".png", iv_user_image);
//        ImageLoader.getInstance().displayImage(MyApplication.getInstance().HostName + "/upload/selficon/" + MyApplication.username + ".png",
//                iv_user_image,
//                MyApplication.getInstance().getImageOptions(
//                        new RoundedBitmapDisplayer(5)));
    }

    private void settTitle() {
        titleBarView = getHeadbar();//父類進行了初始化
        //測試左,中,右邊的文字
        if (titleBarView != null) {
            titleBarView.setLeftAndCenterVisible();
            titleBarView.setTitle("設定個人頭像");
            titleBarView.doBack(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
    }

    private void initView() {
        iv_user_image = (ImageView) findViewById(R.id.iv_user_image);
        btn_camer = (Button) findViewById(R.id.btn_camer);
        btn_camer.setOnClickListener(this);
        btn_photo = (Button) findViewById(R.id.btn_photo);
        btn_photo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_photo:
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                startActivityForResult(intent, ALBUM_REQUEST_CODE);
                break;
            case R.id.btn_camer:
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.
                        getExternalStorageDirectory(), "temp.jpg")));
                startActivityForResult(intent, CAMERA_REQUEST_CODE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case ALBUM_REQUEST_CODE:
                LogUtils.e("相簿 [ " + data + " ]");
                if (data == null) {
                    return;
                }
                startCrop(data.getData());
                break;
            case CAMERA_REQUEST_CODE:
                File picture = new File(Environment.getExternalStorageDirectory()
                        + "/temp.jpg");
                LogUtils.e("相機檔案路徑:" + picture.getAbsolutePath());
                startCrop(Uri.fromFile(picture));
                break;
            case CROP_REQUEST_CODE:
                if (data == null) {
                    // TODO 如果之前以後有設定過顯示之前設定的圖片 否則顯示預設的圖片
                    ImageLoader.getInstance().displayImage("file:///storage/emulated/0/chaoyang/" + MyApplication.username + ".png", iv_user_image);
//                    ImageLoader.getInstance().displayImage("http://172.16.0.180:8080/upload/selficon/" + "default.png",
//                            iv_user_image,
//                            MyApplication.getInstance().getImageOptions(
//                                    new RoundedBitmapDisplayer(5)));
                    return;
                }
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)壓縮檔案
                    File fImage = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/chaoyang/" + MyApplication.username + ".png");
                    try {
                        fImage.createNewFile();
                        FileOutputStream iStream = new FileOutputStream(fImage);
                        photo.compress(Bitmap.CompressFormat.PNG, 100, iStream);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    iv_user_image.setImageBitmap(photo); //把圖片顯示在ImageView控制元件上
                    LogUtils.e("圖片擷取的路徑:" + fImage.getAbsolutePath());
                    loadUserImage(fImage);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 上傳圖片
     */
    public void loadUserImage(File file) {
        showLoad();
        RequestParams requestParams = new RequestParams();
        requestParams.addHeader("Expect", "100-Continue");
        requestParams.addBodyParameter("userid", MyApplication.userid);
        requestParams.addBodyParameter("img", MyApplication.username + ".png");
        requestParams.addBodyParameter("uploadfile", file);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, MyApplication.getInstance().HostName + "/app/user/selfPhoto", requestParams, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                L.e("成功了" + responseInfo.result);
                T.showMyToast(SettingUserImageActivity.this, getResources().getString(R.string.commit_success));
                dismissLoad();
                EventBus.getDefault().post(new MessageEvent(1, "opentask", ""));//圖片設定成功
                onBackPressed();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                T.showMyToast(SettingUserImageActivity.this, getResources().getString(R.string.commit_error));
                LogUtils.e("失敗資料:" + e.toString() + "-----" + s);
                dismissLoad();
            }
        });
    }

    /**
     * 開始裁剪
     *
     * @param uri
     */
    private void startCrop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");//呼叫Android系統自帶的一個圖片剪裁頁面,
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");//進行修剪
        // aspectX aspectY 是寬高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪圖片寬高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }


}
繼承了BaseActivity,就省略。。。。

接下來就是圓形圖片的回現了。。。和初始化網路載入圓形影象

private String path="/storage/emulated/0/chaoyang/";
if (fileIsExists(path + MyApplication.username + ".png")) {
            Bitmap bitmap = getLoacalBitmap(path + MyApplication.username + ".png");
            iv_user_image.setImageBitmap(toRoundCorner(bitmap, 2));
        } else {
            ImageLoader.getInstance().displayImage(MyApplication.getInstance().HostName + "/upload/selficon/" + MyApplication.username + ".png",
                    iv_user_image,
                    getImageOptions(new RoundedBitmapDisplayer(5)));
        }
//判斷檔案是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

/**
     * 圓形
     * @param bitmap
     * @param ratio
     * @return
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, float ratio) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, bitmap.getWidth() / ratio,
                bitmap.getHeight() / ratio, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        System.out.println("pixels+++++++" + String.valueOf(ratio));

        return output;

    }



有時間寫一個demo,還有EventBus事件的傳遞處理,第一次寫部落格,諒解。