Bmob云IM实现头像更换并存入Bmob云数据库中(1.拍照替换,2.相册选择)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Bmob云IM实现头像更换并存入Bmob云数据库中(1.拍照替换,2.相册选择)相关的知识,希望对你有一定的参考价值。

看图效果如下:

1.个人资料界面

2.点击头像弹出对话框

3.点击拍照

4.切割图片,选择合适的部分

 

5.点击保存,头像替换完毕,下面看从相册中选择图片。

6.点击相册

7.任选一张图片

8.切割图片

 

 9.图片替换成功

 

 

 

亲测退出账户后重新登陆或者换模拟器登陆有效!!!

图片已经上传到云端了!!!

 

下面先上xml代码:

里面出现的可能报错的代码都是bmob云IM DEMO照搬的,这里不再提供代码或者图片。

上一个Bmob云IM DEMO下载地址(https://github.com/chaozhouzhang/bmob-newim-demo),这个是官方DEMO

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/my_layout_all"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/theme_bg_color"
              android:orientation="vertical" >

    <include layout="@layout/include_navi"/>

    <RelativeLayout
        android:id="@+id/my_layout_head"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/about_top_bg"
        android:minHeight="80dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" >

        <TextView
            style="@style/style_text_black"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="@string/add_avator" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:gravity="center_vertical"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/my_iv_avator"
                android:layout_alignParentRight="true"
                android:layout_width="@dimen/height_50"
                android:layout_height="@dimen/height_50"
                android:layout_alignParentLeft="true"
                android:layout_marginTop="@dimen/margin_12"
                android:layout_marginBottom="@dimen/margin_12"
                android:layout_marginLeft="@dimen/margin_16"
                android:src="@mipmap/head" />
        </LinearLayout>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/my_layout_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/about_mid_bg"
        android:padding="10dp" >

        <TextView
            style="@style/style_text_black"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="@string/add_name" />

        <TextView
            android:id="@+id/my_tv_name"
            style="@style/style_text_black"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="20dp"
            android:drawablePadding="10dp" />
    </RelativeLayout>


</LinearLayout>

 

 

下面是JAVA代码:

package cn.bmob.imdemo.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.imdemo.R;
import cn.bmob.imdemo.base.ImageLoaderFactory;
import cn.bmob.imdemo.base.ParentWithNaviActivity;
import cn.bmob.imdemo.bean.AddFriendMessage;
import cn.bmob.imdemo.bean.User;
import cn.bmob.imdemo.model.UserModel;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * 用户资料
 */
public class MyUserInfoActivity extends ParentWithNaviActivity {

    @Bind(R.id.my_iv_avator)
    ImageView iv_avator;
    @Bind(R.id.my_tv_name)
    TextView tv_name;


    private File mFile;

    private Bitmap mBitmap;

    String path = "";

    public static final int TAKE_PHOTO = 1;

    public static final int CHOOSE_PHOTO = 2;

    public static final int CUT_PHOTO = 3;

    //用户
    User user;
    //用户信息
    BmobIMUserInfo info;

    @Override
    protected String title() {
        return "个人资料";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_user_info);
        ButterKnife.bind(this);
        //导航栏
        initNaviView();
        //用户
        user = (User) getBundle().getSerializable("u");

        //构造聊天方的用户信息:传入用户id、用户名和用户头像三个参数
        info = new BmobIMUserInfo(user.getObjectId(), user.getUsername(), user.getAvatar());
        //加载头像
        ImageLoaderFactory.getLoader().loadAvator(iv_avator, user.getAvatar(), R.mipmap.head);
        //显示名称
        tv_name.setText(user.getUsername());

        iv_avator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String title = "选择获取图片方式";
                String[] items = new String[]{"拍照", "相册"};

                new AlertDialog.Builder(MyUserInfoActivity.this)
                        .setTitle(title)
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                switch (which) {
                                    case 0:
                                        //选择拍照
                                        pickImageFromCamera();
                                        break;
                                    case 1:
                                        //选择相册
                                        pickImageFromAlbum();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }).show();
            }
        });
    }


    //拍照
    public void pickImageFromCamera(){
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            if (!file.exists()) {
                file.mkdirs();
            }
            mFile = new File(file, System.currentTimeMillis() + ".jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, TAKE_PHOTO);
        } else {
            Toast.makeText(this, "请确认已经插入SD卡", Toast.LENGTH_SHORT).show();
        }
    }
    //从相册获取图片
    public void pickImageFromAlbum(){
        Intent picIntent = new Intent(Intent.ACTION_PICK, null);
        picIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(picIntent, CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    startPhotoZoom(Uri.fromFile(mFile));
                    break;
                case CHOOSE_PHOTO:

                    if (data == null || data.getData() == null) {
                        return;
                    }
                    try {
                        Bitmap bm = null;
                        Uri originalUri = data.getData();        //获得图片的uri


                        bm = MediaStore.Images.Media.getBitmap(getContentResolver(), originalUri);        //显得到bitmap图片


                        //这里开始的第二部分,获取图片的路径:


                        String[] proj = {MediaStore.Images.Media.DATA};


                        //好像是android多媒体数据库的封装接口,具体的看Android文档

                        Cursor cursor = managedQuery(originalUri, proj, null, null, null);

                        //按我个人理解 这个是获得用户选择的图片的索引值

                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                        //将光标移至开头 ,这个很重要,不小心很容易引起越界

                        cursor.moveToFirst();

                        //最后根据索引值获取图片路径

                        path = cursor.getString(column_index);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    startPhotoZoom(data.getData());

                    break;
                case CUT_PHOTO:

                    if (data != null) {
                        setPicToView(data);
                    }
                    break;


            }
        }

    }
    /**
     * 打开系统图片裁剪功能
     *
     * @param uri  uri
     */
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true); //黑边
        intent.putExtra("scaleUpIfNeeded", true); //黑边
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, CUT_PHOTO);

    }
    private void setPicToView(Intent data) {
        Bundle bundle = data.getExtras();
        if (bundle != null) {

//
//            Uri selectedImage = data.getData();
//
//            String[] filePathColumn = { MediaStore.Images.Media.DATA };
//
//            Cursor cursor = getContentResolver().query(selectedImage,
//                    filePathColumn, null, null, null);
//            cursor.moveToFirst();
//
//            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//            String picturePath = cursor.getString(columnIndex);
//

            //这里也可以做文件上传
            mBitmap = bundle.getParcelable("data");
            // ivHead.setImageBitmap(mBitmap);
            iv_avator.setImageBitmap(mBitmap);
//
//            if (picturePath!=null){
//                path = picturePath;
//            }

            if(mFile != null){
                path = mFile.getPath();
            }

            Toast.makeText(MyUserInfoActivity.this,"path:"+path,Toast.LENGTH_SHORT).show();

            final BmobFile bmobFile = new BmobFile(new File(path));
            //Bmob这个上传文件的貌似不成功..........................
            bmobFile.uploadblock(new UploadFileListener() {

                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Toast.makeText(MyUserInfoActivity.this, "pic is success", Toast.LENGTH_SHORT).show();
                        // MyUser myUser =MyUser.getCurrentUser(MyUser.class);
                        //得到上传的图片地址
                        String fileUrl = bmobFile.getFileUrl();
                        user.setAvatar(fileUrl);
                        //更新图片地址
                        user.update(user.getObjectId(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    Toast.makeText(MyUserInfoActivity.this, "update", Toast.LENGTH_SHORT).show();

                                }
                            }
                        });
                    }
                }
            });

        }
    }
}

 

 

 

 我也是参考了N多博客大神的代码才写出来的,写在这供大家参考,希望大家多多发扬开源的精神。

 

以上是关于Bmob云IM实现头像更换并存入Bmob云数据库中(1.拍照替换,2.相册选择)的主要内容,如果未能解决你的问题,请参考以下文章

云数据库 Bmob

Github Page+Bmob实现简单动态功能

bmob后端云可以用来做网页的后端吗

Bmob后端云实现无后端开发APP

请问bmob开发中,如何修改User表中的数据?

Android实战——第三方服务之Bmob后端云的云应用收纳集小项目