这里我正在尝试将图像放入视图但我无法在其中设置图像我正在使用设置圆形视图的第三方库。我在设置图像时出错。
此代码位于主活动中,并在单击按钮时调用。欢迎使用任何代码解决方案
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case PICK_IMAGE_ID :
Bitmap bitmap =ImagePicker.getImageFromResult(this,resultCode,data);
circleImageView.setImageResource(bitmap);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
这是我的图像选择器活动,其中还包含照片修剪,以便不会发送重图像
public class ImagePicker {
private static final String TAG ="ImagePicker";
private static final String TEMP_IMAGE_NAME = "tempImage";
private static Bitmap bm;
private static final int DEFAULT_MIN_WIDTH_QUALITY = 400;
public static int minWidthQuality = DEFAULT_MIN_WIDTH_QUALITY;
public static Intent getImagePicker(Context context){
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent pickIntent = new Intent(Intent.ACTION_PICK , MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra("return-data",true);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
intentList = addIntentToList(context,intentList,pickIntent);
intentList = addIntentToList(context,intentList,takePhotoIntent);
if (intentList.size() > 0){
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() -1),
context.getString(R.string.pick_image_intent_string_text));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
public static List<Intent> addIntentToList (Context context, List<Intent> list,Intent intent){
List<ResolveInfo> resolveInfo = context.getPackageManager().queryIntentActivities(intent,0);
for (ResolveInfo resolveInfos :resolveInfo){
String packageName = resolveInfos.activityInfo.packageName;
Intent targetIntent = new Intent(intent);
targetIntent.setPackage(packageName);
list.add(targetIntent);
Log.d(TAG, "addIntentToList: " +intent.getAction() + " package " + packageName);
}
return list;
}
public static Bitmap getImageFromResult (Context context,int resultCode, Intent imageReturnedIntent){
Log.d(TAG, "getImageFromResult: "+ resultCode);
Bitmap bitmap = null;
File imageFile = getTempFile(context);
if(resultCode == Activity.RESULT_OK){
Uri selectedImage;
boolean isCamera = (imageReturnedIntent == null ||
imageReturnedIntent.getData() == null ||
imageReturnedIntent.getData().toString().contains(imageFile.toString()));
if (isCamera){
selectedImage = Uri.fromFile(imageFile);
}else {
selectedImage = imageReturnedIntent.getData();
}
Log.d(TAG, "getImageFromResult: " + selectedImage);
bm = getImageResized(context, selectedImage);
int rotation = getRotation(context, selectedImage, isCamera);
bm = rotate(bm, rotation);
}
return bm;
}
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private static Bitmap decodeBitmap(Context context,Uri theUri,int sampleSize){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
AssetFileDescriptor assetFileDescriptor = null;
try{
assetFileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri,"r");
}catch (Exception ex){
ex.printStackTrace();
}
Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(assetFileDescriptor.getFileDescriptor(),null,options);
Log.d(TAG, options.inSampleSize + "decodeBitmap: " + actuallyUsableBitmap.getWidth()
+ " " + actuallyUsableBitmap.getHeight());
return actuallyUsableBitmap;
}
/**
* Resize to avoid using too much memory loading big images (e.g.: 2560*1920)
**/
private static Bitmap getImageResized(Context context,Uri selectedImage){
Bitmap bm = null;
int [] sampleSizes =new int[]{5, 3, 2, 1};
int i = 0;
do {
bm = decodeBitmap(context,selectedImage,sampleSizes[i]);
Log.d(TAG, "getImageResized: " +bm.getWidth());
i++;
}while (bm.getWidth() < minWidthQuality && i < sampleSizes.length);
return bm;
}
private static int getRotation(Context context, Uri imageUri, boolean isCamera){
int rotation;
if(isCamera){
rotation = getRotationFromCamera(context,imageUri);
}
else {
rotation = getRotationFromGallery(context,imageUri);
}
Log.d(TAG, "getRotation: " + rotation);
return rotation;
}
private static int getRotationFromCamera(Context context, Uri imageFile) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageFile, null);
ExifInterface exif = new ExifInterface(imageFile.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
public static int getRotationFromGallery(Context context, Uri imageUri) {
int result = 0;
String[] columns = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
result = cursor.getInt(orientationColumnIndex);
}
} catch (Exception e) {
//Do nothing
} finally {
if (cursor != null) {
cursor.close();
}
}//End of try-catch block
return result;
}
private static Bitmap rotate(Bitmap bm, int rotation) {
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Bitmap bmOut = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
return bmOut;
}
return bm;
}
}
此代码在选择图像时工作正常但不能将图像设置为图像视图,并且适用于5.0但是应用程序在JELLY_BEAN上崩溃。
我正在使用第三方库来制作圆形图像
6.0的错误代码
04-15 10:18:47.114 3754-3754/com.example.this_pc.framelayout E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.this_pc.framelayout, PID: 3754
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=234, result=-1, data=Intent { dat=content://media/external/images/media/34 }} to activity {com.example.this_pc.framelayout/com.example.this_pc.framelayout.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileDescriptor android.content.res.AssetFileDescriptor.getFileDescriptor()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileDescriptor android.content.res.AssetFileDescriptor.getFileDescriptor()' on a null object reference
at com.example.this_pc.framelayout.ImagePicker.decodeBitmap(ImagePicker.java:130)
at com.example.this_pc.framelayout.ImagePicker.getImageResized(ImagePicker.java:151)
at com.example.this_pc.framelayout.ImagePicker.getImageFromResult(ImagePicker.java:103)
at com.example.this_pc.framelayout.MainActivity.onActivityResult(MainActivity.java:50)
at android.app.Activity.dispatchActivityResult(Activity.java:6428)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-15 10:18:49.745 3754-3754/com.example.this_pc.framelayout I/Process: Sending signal. PID: 3754 SIG: 9
Error Code for 4.2 a.k.a JELLY_BEAN
04-15 10:11:48.709 12956-12956/com.example.this_pc.framelayout
E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException
at com.example.this_pc.framelayout.ImagePicker.getTempFile(ImagePicker.java:112) at com.example.this_pc.framelayout.ImagePicker.getImagePicker(ImagePicker.java:48 )
at com.example.this_pc.framelayout.MainActivity$1.onClick(MainActivity.java:37)
at android.view.View.performClick(View.java:4432) at
android.view.View$PerformClick.run(View.java:18338) at
android.os.Handler.handleCallback(Handler.java:725) at
android.os.Handler.dispatchMessage(Handler.java:92) at
android.os.Looper.loop(Looper.java:137) at
android.app.ActivityThread.main(ActivityThread.java:5283) at
java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:511) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) at
dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
使用setImageBitmap而不是setImageResource
setImageResource期望资源作为属性,在本例中为整数id
imageView.setImageResource(int resId)
您将位图作为属性,因此请使用setImageBitmap
imageView.setImageBitmap(Bitmap bitmap);
答案 1 :(得分:0)
您需要设置Bitmap
作为此ImageView
的内容。
因此,请尝试setImageBitmap()
而不是setImageResource()
,如下所示:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case PICK_IMAGE_ID :
Bitmap bitmap =ImagePicker.getImageFromResult(this,resultCode,data);
circleImageView.setImageBitmap(bitmap);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}