今天在做上传头像的时候遇到这个坑。(调试阶段,我的手机是好的,别的手机是坏的(坏手机是三星,坏透了))
出现这种原因:首先要想到的是你自己创建了一级子目录,比如,我就创建了一级目录,用于存放项目图片,代码如下
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
CACHE_DIR = Environment.getExternalStorageDirectory() + "/logistics";
} else {
CACHE_DIR = Environment.getRootDirectory() + "/logistics";
}
CACHE_DIR_UPLOADING_IMG = CACHE_DIR + "";
File file=new File(CACHE_DIR);
if (!file.exists()) {
file.mkdirs();
}
此时,在此目录下,都要判断是否已经创建过文件夹。此为一坑,这个坑比较容易解决。
事实上,我现在是不可能犯这种错误的,于是,报这个异常的时候,整个人都要蒙调了。跟后台一顿调试,最终找到原因:
此bug主要出现在调用系统相册图片,我没调用系统裁剪,用的是自己的压缩工具在
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
中 选择图库图片返回的是uri。我用的压缩思路是根据图片路径,保存到新路径。就是这个原图片路径出问题了。下为我原来调用代码:
private void compressImg(final Uri uri) {
new Thread(new Runnable() {
@Override
public void run() {
ImageCutCompressUtils.getSmallImage(uri.getPath(), FILE_PATH);
runOnUiThread(new Runnable() {
@Override
public void run() {
returnPath();
}
});
}
}).start();
}
大家注意我传入的uri。血泪教训啊,并不是一个正确格式的uri(最起码 的适配工作都没搞,找了几个小时的bug才定位到这里,苦。)
正确格式的uri应当是这个样子的
private void compressImg(final Uri uri) {
new Thread(new Runnable() {
@Override
public void run() {
ImageCutCompressUtils.getSmallImage(getPath(PanoramaSetActivity.this,uri), FILE_PATH);
runOnUiThread(new Runnable() {
@Override
public void run() {
returnPath();
}
});
}
}).start();
}
只是uri的方式换了。
下面贴出获取uri的代码大家保存到工具类 就可以
@SuppressLint("NewApi")
public String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
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];
}
} 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);
} 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);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
public 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;
}
如果缺那个方法了,请给我留言。下面贴出来我的压缩代码
// TODO: 2016/10/25 传入保存图片路径要传全路径 尽量使用保存成新图片的方式,不保存新图片即getSmallImage(String filePath) 方法,会覆盖原有图片
public class ImageCutCompressUtils {
/**
* 原路径保存调用
* @param filePath 图片路径
*/
public static void getSmallImage(String filePath) {
//裁剪
compressImage(getSmallBitmap(filePath),filePath);
}
/**
* 保存新路径图片
* @param filePath 图片路径
* @param savePath 保存图片路径
*/
public static void getSmallImage(String filePath,String savePath) {
//裁剪
compressImage(getSmallBitmap(filePath),filePath,savePath);
}
private static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeFile(filePath,options);
options.inSampleSize=calculateInSampleSize(options, 240, 400);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
/**
* 计算图片缩放值
* @param options 配置对象
* @param reqWidth 宽
* @param reqHeight 高
* @return 缩放比
*/
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* 原路径保存
* @param bm
* @param savePath
*/
public static void compressImage(Bitmap bm,String savePath) {
int options=100;
ByteArrayOutputStream baos =new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,options, baos);
//目前 压缩标准200K
while (baos.toByteArray().length>1024*200) {
baos.reset();
bm.compress(Bitmap.CompressFormat.JPEG, options, baos);
options-=10;
}
saveBitmap(bm, savePath);
}
/**
* 创建新路径保存
* @param bm
* @param savePath
*/
public static void compressImage(Bitmap bm,String filePath,String savePath) {
int options=100;
ByteArrayOutputStream baos =new ByteArrayOutputStream();
if (bm == null) {
return;
}
bm.compress(Bitmap.CompressFormat.JPEG,options, baos);
//目前 压缩标准300K
while (baos.toByteArray().length>1024*300) {
baos.reset();
bm.compress(Bitmap.CompressFormat.JPEG, options, baos);
options-=10;
}
saveBitmap(bm, filePath,savePath);
}
private static void saveBitmap(Bitmap bm,String filePath) {
Bitmap mBitmap= getRotateBM(bm, filePath);
File file=new File(filePath);
if (file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file) ;
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private static void saveBitmap(Bitmap bm,String filePath,String savePath) {
Bitmap mBitmap= getRotateBM(bm, filePath);
File file=new File(savePath);
if (file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file) ;
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private static Bitmap getRotateBM(Bitmap bm, String path) {
int degree=getRotateDegree(path);
if (degree != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap mBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
return mBitmap;
} else {
return bm;
}
}
/**
* 获取图片旋转角度(TMD三星和小米等手机会搞事情)
* @param path 图片路径
* @return 旋转角度
*/
private static int getRotateDegree(String path) {
int degree=0;
try {
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;
}
}
目前 还没找到什么bug,如果大家使用中有什么问题,请留言。