工具類---上傳頭像
阿新 • • 發佈:2018-11-13
-
-
呼叫系統相簿
protected void gotoXC() {
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra ("aspectY", 1);
intent.putExtra("outputX", 80);
intent.putExtra("outputY", 80);
intent.putExtra("return-data", true);
startActivityForResult(intent, 0);
}
呼叫照相機
protected void gotoXJ() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1 );
}
獲取圖片儲存到本地 並顯示到imageview
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==Activity.RESULT_OK){
Log.e(“onActivityResult”, resultCode+”“);
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 檢測sd是否可用
Log.i(“TestFile”,
“SD card is not avaiable/writeable right now.”);
Log.e(“onActivityResult”, “SD card is not avaiable/writeable right now”);
return;
}
String name = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");// 獲取相機返回的資料,並轉換為Bitmap圖片格式
FileOutputStream b = null;
File file = new File("/sdcard/myImage/");
file.mkdirs();// 建立資料夾
String fileName = "/sdcard/myImage/"+name;
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把資料寫入檔案
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("onActivityResult", "----------------001");
//===呼叫介面儲存頭像 成功更換頭像
if(true){
Log.e("onActivityResult", "---------------------002");
Drawable drawable =new BitmapDrawable(bitmap);
image_avtr.setBackground(null);
image_avtr.setImageBitmap(null);
image_avtr.setImageDrawable(null);
image_avtr.setBackgroundDrawable(null);
image_avtr.setBackground(drawable);
}else{
ToastUtils.Toas(getApplicationContext(), "上傳頭像失敗,請稍後再試");
}else{
ToastUtils.Toas(getApplicationContext(), "照片獲取失敗,請稍後再試");
}
}
許可權
<!-- 呼叫系統相機許可權 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />