上传图片到服务器---from--data格式

本文介绍了一个简单的头像上传和裁剪功能实现方法,包括使用PopupWindow弹窗选择图片来源、通过相册选取或相机拍摄获取图片、对图片进行裁剪并上传到服务器的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中都会有修改头像,上传照片到服务器的功能,简单来一个,可以直接用。xutils

public class UserMsgActivity extends BaseActivity {

   

    private CircleImageView pic;//头像
   

    // 声明PopupWindow
    private PopupWindow popupWindow;
    // 声明PopupWindow对应的视图
    private View popupView;
    // 声明平移动画
    private TranslateAnimation animation;

    private String path = "/sdcard/myHeadPic/";// sd路径
    private Bitmap head;//头像Bitmap
    private String mFilePath;

    private boolean picFlag = false;
    private String s;

    private String imageUrl;
   
    @Override
    public int getLayoutId() {
        return R.layout.activity_user_msg;
    }

    @Override
    public void initViews() {
        Intent intent = getIntent();
        imageUrl = intent.getStringExtra("imageUrl");
        
        // 文件名
        mFilePath = path + "userhead.jpg";

       

        pic = findView(R.id.pic);
       
        Logger.e("imsgeUrl--" + imageUrl);
        //设置头像,昵称,邮箱
        if (imageUrl != null && !imageUrl.equals("")) {
            Glide.with(this).load(imageUrl).into(pic);
        } else {
            //没头像展示默认
            pic.setImageResource(R.drawable.nologin_pic);
        }
       
    }

    @Override
    public void initListener() {
        
        setOnClick(pic);
        
    }

    @Override
    public void initData() {

    }

    @Override
    public void progressClick(View v) {
        switch (v.getId()) {
            
            case R.id.pic://修改图片
                changeIcon();
                break;
            
          
        }
    }

    /**
     * 弹出popupWindow
     */
    private void changeIcon() {
        lightoff();
        if (popupWindow == null) {
            popupView = View.inflate(this, R.layout.popup_uploading, null);
            // 参数2,3:指明popupwindow的宽度和高度
            popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);

            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    popupWindow = null;

                    lighton();
                }
            });

            // 设置背景图片,必须设置,不然动画没作用
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setFocusable(true);

            // 设置点击popupwindow外屏幕其它地方消失
            popupWindow.setOutsideTouchable(true);

            // 平移动画相对于手机屏幕的底部开始,X轴不变,Y轴从10
            animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                    Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT, 0);
            animation.setInterpolator(new AccelerateInterpolator());
            animation.setDuration(200);
            //退出
            popupView.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                    lighton();
                }
            });
            //从相册选择
            popupView.findViewById(R.id.photo_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent1, 1);

                    popupWindow.dismiss();
                    lighton();
                }
            });
            //拍照
            popupView.findViewById(R.id.take_pic).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    //// 指定存储路径,这样就可以保存原图了
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "userhead.jpg")));
                    startActivityForResult(intent2, 2);// 采用ForResult打开

                    popupWindow.dismiss();
                    lighton();
                }
            });
        }

        // 在点击之后设置popupwindow的销毁
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
            lighton();
        }

        // 设置popupWindow的显示位置,此处是在手机屏幕底部且水平居中的位置
        popupWindow.showAtLocation(pic, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        popupView.startAnimation(animation);
    }

    /**
     * 设置手机屏幕亮度变暗
     */
    private void lightoff() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);
    }

    /**
     * 设置手机屏幕亮度显示正常
     */
    private void lighton() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f;
        getWindow().setAttributes(lp);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1://相册
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());// 裁剪图片
                    Log.e("--main--", "--11---22--" + data.getData());
                }
                break;
            case 2://拍照
                if (resultCode == RESULT_OK) {
                    //;这个是设置文件名
                    File temp = new File(Environment.getExternalStorageDirectory() + "/userhead.jpg");
                    cropPhoto(Uri.fromFile(temp));// 裁剪图片
                    Log.e("--main--", "--33--55--" + Uri.fromFile(temp));
                }
                break;
            case 3://裁剪
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        setPicToView(head);// 保存在SD卡中
                        /**
                         * 上传服务器代码
                         */
                        s = PictureUtils.compressImage(mFilePath);
                        picFlag = true;
                        Log.e("--main--", "-3333--6666--" + PictureUtils.compressImage(mFilePath));
                        pic.setImageBitmap(head);// ImageView显示出来

                        if (s != null) {
                            uploadPicture(s);
                        }
                    }
                }
                break;
            default:
                break;
        }
        //修改昵称返回
        if (requestCode == 2333 && resultCode == 3332) {
            String name = data.getStringExtra("name");
            user_name.setText(name);
        }
        //修改邮箱返回
        if (requestCode == 2666 && resultCode == 6662) {
            String email = data.getStringExtra("email");
            user_email.setText(email);
        }

    }

    private void uploadPicture(String s) {
        if (!picFlag) {
            ToastUtil.showToast("请上传照片");
            return;
        }
        Logger.e("修改头像接口--" + UrlUtils.editUserMsgUrl);

        RequestParams params = new RequestParams();
        params.addHeader("token", SharePrefManager.getToken());
        params.addHeader("userId", SharePrefManager.getUserId());

        HttpUtils xhttp = new com.lidroid.xutils.HttpUtils();
        File file = new File(s);
        params.addBodyParameter("userId", SharePrefManager.getUserId());
        params.addBodyParameter("type", "1");
        params.addBodyParameter("icon", file);

        xhttp.send(HttpRequest.HttpMethod.POST, UrlUtils.editUserMsgUrl, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Logger.e("post-修改头像数据--" + responseInfo.result);
                Gson gson = new Gson();
                Modification modification = gson.fromJson(responseInfo.result, Modification.class);
                if (modification != null && modification.getCode().equals("0000")) {
                    ToastUtil.showToast("修改头像成功");
                } else {
                    ToastUtil.showToast("修改头像失败,请重试");
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtil.showToast("网络错误,请检查网络");
                Logger.e("post-修改头像--error");
            }

        });
    }

    /**
     * 将图片保存到SD卡上面
     *
     * @param
     */
    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            ToastUtil.showToast("SD卡不可用");
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "userhead.jpg";// 图片名字
        Log.e("--main--", fileName + "--==----111");
        try {
            b = new FileOutputStream(fileName);
            //2个参数表示压缩率,100表示不压缩
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (b != null) {
                    b.flush();
                    b.close();
                    b = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 裁剪图片
    private void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值