Bmob雲IM實現頭像更換並存入Bmob雲數據庫中(1.拍照替換,2.相冊選擇)

看圖效果以下:java

1.我的資料界面android

2.點擊頭像彈出對話框git

3.點擊拍照github

4.切割圖片,選擇合適的部分數據庫

 

5.點擊保存,頭像替換完畢,下面看從相冊中選擇圖片。app

6.點擊相冊ide

7.任選一張圖片ui

8.切割圖片this

 

 9.圖片替換成功spa

 

 

 

親測退出帳戶後從新登錄或者換模擬器登錄有效!!!

圖片已經上傳到雲端了!!!

 

下面先上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多博客大神的代碼才寫出來的,寫在這供你們參考,但願你們多多發揚開源的精神。

相關文章
相關標籤/搜索