Bmob云IM实现头像更换并存入Bmob云数据库中(1.拍照替换,2.相册选择)
生活随笔
收集整理的這篇文章主要介紹了
Bmob云IM实现头像更换并存入Bmob云数据库中(1.拍照替换,2.相册选择)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
看圖效果如下:
1.個(gè)人資料界面
2.點(diǎn)擊頭像彈出對(duì)話框
3.點(diǎn)擊拍照
4.切割圖片,選擇合適的部分
?
5.點(diǎn)擊保存,頭像替換完畢,下面看從相冊(cè)中選擇圖片。
6.點(diǎn)擊相冊(cè)
7.任選一張圖片
8.切割圖片
?
?9.圖片替換成功
?
?
?
親測(cè)退出賬戶后重新登陸或者換模擬器登陸有效!!!
圖片已經(jīng)上傳到云端了!!!
?
下面先上xml代碼:
里面出現(xiàn)的可能報(bào)錯(cuò)的代碼都是bmob云IM DEMO照搬的,這里不再提供代碼或者圖片。
上一個(gè)Bmob云IM DEMO下載地址(https://github.com/chaozhouzhang/bmob-newim-demo),這個(gè)是官方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"/><RelativeLayoutandroid: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" ><TextViewstyle="@style/style_text_black"android:layout_alignParentLeft="true"android:layout_centerVertical="true"android:text="@string/add_avator" /><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:gravity="center_vertical"android:orientation="horizontal" ><ImageViewandroid: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><RelativeLayoutandroid:id="@+id/my_layout_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@drawable/about_mid_bg"android:padding="10dp" ><TextViewstyle="@style/style_text_black"android:layout_alignParentLeft="true"android:layout_centerVertical="true"android:text="@string/add_name" /><TextViewandroid: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;@Overrideprotected String title() {return "個(gè)人資料";}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_my_user_info);ButterKnife.bind(this);//導(dǎo)航欄 initNaviView();//用戶user = (User) getBundle().getSerializable("u");//構(gòu)造聊天方的用戶信息:傳入用戶id、用戶名和用戶頭像三個(gè)參數(shù)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() {@Overridepublic void onClick(View view) {String title = "選擇獲取圖片方式";String[] items = new String[]{"拍照", "相冊(cè)"};new AlertDialog.Builder(MyUserInfoActivity.this).setTitle(title).setItems(items, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();switch (which) {case 0://選擇拍照 pickImageFromCamera();break;case 1://選擇相冊(cè) 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, "請(qǐng)確認(rèn)已經(jīng)插入SD卡", Toast.LENGTH_SHORT).show();}}//從相冊(cè)獲取圖片public void pickImageFromAlbum(){Intent picIntent = new Intent(Intent.ACTION_PICK, null);picIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");startActivityForResult(picIntent, CHOOSE_PHOTO);}@Overrideprotected 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多媒體數(shù)據(jù)庫的封裝接口,具體的看Android文檔 Cursor cursor = managedQuery(originalUri, proj, null, null, null);//按我個(gè)人理解 這個(gè)是獲得用戶選擇的圖片的索引值int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//將光標(biāo)移至開頭 ,這個(gè)很重要,不小心很容易引起越界 cursor.moveToFirst();//最后根據(jù)索引值獲取圖片路徑 path = cursor.getString(column_index);}catch (Exception e){e.printStackTrace();}startPhotoZoom(data.getData());break;case CUT_PHOTO:if (data != null) {setPicToView(data);}break;}}}/*** 打開系統(tǒng)圖片裁剪功能** @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這個(gè)上傳文件的貌似不成功..........................bmobFile.uploadblock(new UploadFileListener() {@Overridepublic 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() {@Overridepublic void done(BmobException e) {if (e == null) {Toast.makeText(MyUserInfoActivity.this, "update", Toast.LENGTH_SHORT).show();}}});}}});}} }?
?
?
?我也是參考了N多博客大神的代碼才寫出來的,寫在這供大家參考,希望大家多多發(fā)揚(yáng)開源的精神。
?
總結(jié)
以上是生活随笔為你收集整理的Bmob云IM实现头像更换并存入Bmob云数据库中(1.拍照替换,2.相册选择)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Studio安装应用时报
- 下一篇: 51nod 1414 冰雕 思路:暴力模