图片来源弹出窗
// 选择图片来源
public class PopupWindows extends PopupWindow implements View.OnClickListener
{
public PopupWindows(Context mContext, View parent)
{
View view = View.inflate(mContext, R.layout.item_popupwindows, null);
view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));
setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
setBackgroundDrawable(new BitmapDrawable());
setFocusable(true);
setOutsideTouchable(true);
setContentView(view);
showAtLocation(parent, Gravity.BOTTOM, 0, 0);
update();
Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
try {
switch (v.getId())
{
case R.id.item_popupwindows_camera:// 拍照
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 判断存储卡是否可以用,可用进行存储
if (FileUtils.hasSdcard())
{
File dir=new File(imageFilePath);
if(!dir.exists()){
dir.mkdirs();
}
intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, FileUtils.getImageContentUri(EditPersonalActivity.this,imageFilePath));
}
startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE);
break;
case R.id.item_popupwindows_Photo:// 相册
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
startActivityForResult(intent, SELECT_PIC_KITKAT);
}
else
{
startActivityForResult(intent, IMAGE_REQUEST_CODE);
}
break;
}
dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
选择后返回,及头像裁剪和上传:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
// 结果码不等于取消时候
try
{
switch (requestCode)
{
case IMAGE_REQUEST_CODE:
if (isDataNull(data))
{
return;
}
startPhotoZoom(data.getData());
break;
case SELECT_PIC_KITKAT:
if (isDataNull(data))
{
return;
}
startPhotoZoom(data.getData());
break;
case CAMERA_REQUEST_CODE:
if (FileUtils.hasSdcard())
{
startPhotoZoom(FileUtils.getImageContentUri(EditPersonalActivity.this,imageFilePath));
// 上传照片
// setAndUploadPhoto();
}
else
{
HLog.toast(EditPersonalActivity.this, R.string.no_sdcard);
}
break;
case RESULT_REQUEST_CODE:
HLog.toast(EditPersonalActivity.this,"data="+data);
if (isDataNull(data))
{
return;
}else{
setPicToView(data);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 判断是否为空
* @param data
* @return
*/
private boolean isDataNull(Intent data){
if(null==data){
HLog.toast(this,R.string.load_image_failed);
return true;
}else{
return false;
}
}
/**
* 裁剪图片方法实现
*
* @param uri
*/
public void startPhotoZoom(Uri uri)
{
if (uri == null)
{
HLog.toast(this, "The uri is not exist.");
return;
}
HLog.showToast(this,"图片:"+uri.getPath(),Toast.LENGTH_SHORT);
// Intent intent = new Intent("com.android.camera.action.CROP");
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
// {
// String url = getPath(this, uri);
// intent.setDataAndType(FileUtils.getImageContentUri(EditPersonalActivity.this,url), "image/*");
// }
// else
// {
// intent.setDataAndType(uri, "image/*");
// }
// // 设置裁剪
// intent.putExtra("crop", "true");
// // aspectX aspectY 是宽高的比例
// intent.putExtra("aspectX", 1);
// intent.putExtra("aspectY", 1);
// // outputX outputY 是裁剪图片宽高
// intent.putExtra("outputX", 320);
// intent.putExtra("outputY", 320);
// intent.putExtra("return-data", true);
// intent.putExtra("scale", true);
// startActivityForResult(intent, RESULT_REQUEST_CODE);
// cropImagePath = file.getAbsolutePath();
Intent intent = new Intent("com.android.camera.action.CROP");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
String url = getPath(this, uri);
intent.setDataAndType(FileUtils.getImageContentUri(EditPersonalActivity.this,url), "image/*");
}
else
{
intent.setDataAndType(uri, "image/*");
}
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 320);
intent.putExtra("outputY", 320);
intent.putExtra("return-data", true);
startActivityForResult(intent, RESULT_REQUEST_CODE);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri)
{
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri))
{
// ExternalStorageProvider
if (isExternalStorageDocument(uri))
{
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type))
{
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri))
{
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri))
{
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type))
{
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
else if ("video".equals(type))
{
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
else if ("audio".equals(type))
{
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]
{ split[1] };
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme()))
{
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme()))
{
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs)
{
Cursor cursor = null;
final String column = "_data";
final String[] projection =
{ column };
try
{
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst())
{
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
}
finally
{
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri)
{
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri)
{
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri)
{
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* 保存裁剪之后的图片数据
*
* @param picdata
*/
private void setPicToView(Intent picdata)
{
Bundle extras = picdata.getExtras();
if (extras != null)
{
Bitmap photo = extras.getParcelable("data");
HLog.toast(this,"photo="+photo);
File file = FileUtils.saveBitmapToPNG(photo, IMAGE_FILE_NAME);
updatePhoto(file);
if(photo!=null){
Drawable drawable = new BitmapDrawable(photo);
head_icon.setImageDrawable(drawable);//显示头像
}
photo = null;
}
}
/**
* 上传图片
*/
private void updatePhoto(File file)
{
HLog.toast(this,"updatePhoto file="+file);
if (file==null||!file.exists())
{
HLog.showToast(this, R.string.file_not_exists, Toast.LENGTH_SHORT);
return;
}
HashMap paramsMap=new HashMap();
paramsMap.put("uploadFile", file);
paramsMap.put("type", 3);
paramsMap.put("userId", PreferenceUtil.getString(this,PreferenceUtil.USERID,null));
final LoadingDialog loadingDialog=new LoadingDialog(this,res.getString(R.string.uploading_image));
loadingDialog.setCanceledOnTouchOutside(false);
Callback callback=new Callback(){
@Override
public void onFailure(Request request, IOException e) {
EditPersonalActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
loadingDialog.cancel();
HLog.showToast(EditPersonalActivity.this, R.string.getinfo_failed_check_network, Toast.LENGTH_SHORT);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
@Override
public void onResponse(final Response response) throws IOException {
EditPersonalActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
loadingDialog.cancel();
final JSONObject jsonObject=new JSONObject(response.body().string());
HLog.v(TAG,"jsonObject","jsonObject"+jsonObject.toString());
String error = jsonObject.optString("error");
if(!TextUtils.isEmpty(error)){
HLog.toast(EditPersonalActivity.this,error);
return;
}
JSONObject result=jsonObject.optJSONObject("result");
String url=result.optString("url");
PreferenceUtil.setString(EditPersonalActivity.this,PreferenceUtil.USER_IMAGE_URL,url);
HLog.toast(EditPersonalActivity.this,R.string.upload_head_icon_success);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
OkHttpUtil.upLoadFile(Urls.getUploadFileHostAddress(),paramsMap,callback);
}
// 头像上传相关 start
private final String IMAGE_FILE_NAME = "head_icon.png";
private String imageFilePath = FileUtils.SDPATH + IMAGE_FILE_NAME;
/* 请求码 */
private final int IMAGE_REQUEST_CODE = 0;
private final int CAMERA_REQUEST_CODE = 1;
private final int RESULT_REQUEST_CODE = 2;
private final int SELECT_PIC_KITKAT = 3;
public static final String SDPATH = Environment.getExternalStorageDirectory() + "/com.sr.trawms/images/";
FileUtils:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class FileUtils {
private static final String TAG = "FileUtils";
public static final String SDPATH = Environment.getExternalStorageDirectory() + "/com.test/images/";
/**
* 检查是否存在SDCard
*
* @return
*/
public static boolean hasSdcard() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
public static void saveBitmap(Bitmap bm, String picName) {
Log.e("", "保存图片");
try {
if (!isFileExist("")) {
File tempf = createSDDir("");
}
File f = new File(SDPATH, picName + ".png");
if (f.exists()) {
f.delete();
}
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.e("", "已经保存");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//保存图片到本地
public static String saveBitmapBackPath(Bitmap bm, String picName) {
Log.e("", "保存图片");
String filePath = null;
try {
if (!isFileExist("")) {
File tempf = createSDDir("");
}
filePath = SDPATH + picName + ".png";
File f = new File(filePath);
if (f.exists()) {
f.delete();
}
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.e("", "已经保存");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
public static String saveBitmapBackPath(Bitmap bm, String picName, int pressNum) {
Log.e("", "保存图片");
String filePath = null;
try {
if (!isFileExist("")) {
File tempf = createSDDir("");
}
filePath = SDPATH + picName + ".png";
File f = new File(filePath);
if (f.exists()) {
f.delete();
}
FileOutputStream out = new FileOutputStream(f);
if (pressNum > 100 || pressNum < 0) {
pressNum = 100;
}
bm.compress(Bitmap.CompressFormat.PNG, pressNum, out);
out.flush();
out.close();
Log.e("", "已经保存");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
public static File saveBitmapToPNG(Bitmap bm, String picName) {
Log.e("", "保存图片");
File f = null;
try {
if (!isFileExist("")) {
File tempf = createSDDir("");
}
f = new File(SDPATH, picName);
if (f.exists()) {
f.delete();
}
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.e("", "已经保存");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return f;
}
public static File createSDDir(String dirName) throws IOException {
File dir = new File(SDPATH + dirName);
System.out.println("dir=" + dir);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if (!dir.exists()) {
System.out.println("createSDDir:" + dir.getAbsolutePath());
System.out.println("createSDDir:" + dir.mkdirs());
}
} else {
System.out.println("无存储卡!");
}
return dir;
}
public static boolean createSDDir(String dirName, Context context) throws IOException {
File dir = new File(SDPATH + dirName);
System.out.println("dir=" + dir);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if (!dir.exists()) {
System.out.println("createSDDir:" + dir.getAbsolutePath());
System.out.println("createSDDir:" + dir.mkdirs());
return true;
}
} else {
Toast.makeText(context, "没有存储卡!", Toast.LENGTH_SHORT).show();
context = null;
return false;
}
return false;
}
public static boolean isFileExist(String fileName) {
File file = new File(SDPATH + fileName);
file.isFile();
return file.exists();
}
public static void delFile(String fileName) {
File file = new File(SDPATH + fileName);
if (file.isFile()) {
file.delete();
}
file.exists();
}
public static void deleteDir() {
try {
File dir = new File(SDPATH);
if (dir == null || !dir.exists() || !dir.isDirectory())
return;
for (File file : dir.listFiles()) {
if (file.isFile())
file.delete(); // 删除所有文件
// else if (file.isDirectory())
// deleteDir(); // 递规的方式删除文件夹
}
} catch (Exception e) {
e.printStackTrace();
}
// dir.delete();// 删除目录本身
}
public static boolean fileIsExists(String path) {
try {
File f = new File(path);
if (!f.exists()) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 根据路径返回文件File类型
*
* @param filepath 文件绝对路径
* @return
*/
public static File getFileByFilePath(String filepath) {
File file = new File(filepath);
return file;
}
/**
* 读取图片的旋转的角度
*
* @param path 图片绝对路径
* @return 图片的旋转角度
*/
public static int getBitmapDegree(String path) {
int degree = 0;
try {
HLog.v(TAG, "getBitmapDegree", "path=" + path);
File file = new File(path);
if (!file.exists()) {//文件不存在返回
return 0;
}
// 从指定路径下读取图片,并获取其EXIF信息
ExifInterface exifInterface = new ExifInterface(path);
// 获取图片的旋转信息
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 将图片按照某个角度进行旋转
*
* @param bm 需要旋转的图片
* @param degree 旋转角度
* @return 旋转后的图片
*/
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
// 根据旋转角度,生成旋转矩阵
Matrix matrix = new Matrix();
matrix.postRotate(degree);
try {
// 将原始图片按照旋转矩阵进行旋转,并得到新的图片
bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
} catch (OutOfMemoryError e) {
}
return bm;
}
//查询文件大小相关
public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值
/**
* 获取文件指定文件的指定单位的大小
*
* @param filePath 文件路径
* @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
* @return double值的大小
*/
public static double getFileOrFilesSize(String filePath, int sizeType) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
} else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("获取文件大小", "获取失败!");
}
return FormetFileSize(blockSize, sizeType);
}
/**
* 调用此方法自动计算指定文件或指定文件夹的大小
*
* @param filePath 文件路径
* @return 计算好的带B、KB、MB、GB的字符串
*/
public static String getAutoFileOrFilesSize(String filePath) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
} else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("获取文件大小", "获取失败!");
}
return FormetFileSize(blockSize);
}
/**
* 获取指定文件大小
*
* @return
* @throws Exception
*/
private static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
file.createNewFile();
Log.e("获取文件大小", "文件不存在!");
}
return size;
}
/**
* 获取指定文件夹
*
* @param f
* @return
* @throws Exception
*/
private static long getFileSizes(File f) throws Exception {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSizes(flist[i]);
} else {
size = size + getFileSize(flist[i]);
}
}
return size;
}
/**
* 转换文件大小
*
* @param fileS
* @return
*/
private static String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
}
return fileSizeString;
}
/**
* 转换文件大小,指定转换的类型
*
* @param fileS
* @param sizeType
* @return
*/
private static double FormetFileSize(long fileS, int sizeType) {
DecimalFormat df = new DecimalFormat("#.00");
double fileSizeLong = 0;
switch (sizeType) {
case SIZETYPE_B:
fileSizeLong = Double.valueOf(df.format((double) fileS));
break;
case SIZETYPE_KB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
break;
case SIZETYPE_MB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
break;
case SIZETYPE_GB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
break;
default:
break;
}
return fileSizeLong;
}
/**
* 获取文件夹大小
*
* @param file File实例
* @return long
*/
public static long getFolderSize(File file) {
long size = 0;
try {
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isDirectory()) {
size = size + getFolderSize(fileList[i]);
} else {
size = size + fileList[i].length();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return size/1048576;
return size;
}
/**
* 删除指定目录下文件及目录
*/
public void deleteFolderFile(String filePath, boolean deleteThisPath) {
if (!TextUtils.isEmpty(filePath)) {
try {
File file = new File(filePath);
if (file.isDirectory()) {// 处理目录
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFolderFile(files[i].getAbsolutePath(), true);
}
}
if (deleteThisPath) {
if (!file.isDirectory()) {// 如果是文件,删除
file.delete();
} else {// 目录
if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除
file.delete();
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 格式化单位
*
* @param size
* @return
*/
public static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return "";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "K";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "M";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "G";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "T";
}
/**
* 通过文件路径获取URI
*
* @param context
* @param imageFilePath
* @return
*/
public static Uri getUriFromPath(Context context, String imageFilePath) {
Uri photoURI = null;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
photoURI = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", new File(imageFilePath));
} else {
photoURI = Uri.fromFile(new File(imageFilePath));
}
} catch (Exception e) {
e.printStackTrace();
}
return photoURI;
}
/**
* 转换 content:// uri
*
* @param imageFilePath
* @return
*/
public static Uri getImageContentUri(Context context,String imageFilePath) {
File imageFile=new File(imageFilePath);
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
}