2014-10-28 76 views
0

我想设置我的imageButtons图像,当用户从图库中选择一张照片或正在使用相机拍照时。问题是我的imageButtons只是变成了一个空白图像,但我正在获取文件目录。我究竟做错了什么?我从这个答案camera & gallery创建了我的ImageIntent和onActivityResult。但这里是我的onActivityResult方法:setImageURI无法正常工作

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    if (resultCode == RESULT_OK) { 
     if (requestCode == REQUEST_IMAGE_CAPTURE) { 
      final boolean isCamera; 
      if (data == null) { 
       isCamera = true; 
      } else { 
       final String action = data.getAction(); 
       if (action == null) { 
        isCamera = false; 
       } else { 
        isCamera = action 
          .equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       } 
      } 

      Uri selectedImageUri; 
      if (isCamera) { 
       selectedImageUri = outputFileUri; 
      } else { 
       selectedImageUri = data == null ? null : data.getData(); 
      } 

      ImageButton pic1 = (ImageButton) findViewById(R.id.ibPic1); 
      Toast.makeText(this, "Image saved to:\n" + selectedImageUri, 
        Toast.LENGTH_LONG).show(); 
      pic1.setImageURI(selectedImageUri); 
     } 
    } 
} 

所以我从我收到的URI的吐司知道。我试过this answer以及其他各种涉及某种Bitmap的解决方案,但这些解决方案总是导致应用程序崩溃和内存不足异常。

编辑

OnClick方法来启动图像意图:

public void onClick(View v) { 
    // TODO Auto-generated method stub 
    switch (v.getId()) { 
    case R.id.ibPic1: 
     openImageIntent(); 
     break; 
    } 
} 

图像意图方法

private void openImageIntent() { 

    // Determine Uri of camera image to save. 
    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "Klea" + File.separator); 
    root.mkdirs(); 
    final String fname = Sell.getUniqueImageFilename(); 
    final File sdImageMainDirectory = new File(root, fname); 
    outputFileUri = Uri.fromFile(sdImageMainDirectory); 

    // Camera. 
    final List<Intent> cameraIntents = new ArrayList<Intent>(); 
    final Intent captureIntent = new Intent(
      android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
    final PackageManager packageManager = getPackageManager(); 
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(
      captureIntent, 0); 
    for (ResolveInfo res : listCam) { 
     final String packageName = res.activityInfo.packageName; 
     final Intent intent = new Intent(captureIntent); 
     intent.setComponent(new ComponentName(res.activityInfo.packageName, 
       res.activityInfo.name)); 
     intent.setPackage(packageName); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
     cameraIntents.add(intent); 
    } 
    // Filesystem. 
    final Intent galleryIntent = new Intent(); 
    galleryIntent.setType("image/*"); 
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT); 

    // Chooser of filesystem options. 
    final Intent chooserIntent = Intent.createChooser(galleryIntent, 
      "Vælg kilde"); 

    // Add the camera options. 
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, 
      cameraIntents.toArray(new Parcelable[] {})); 

    startActivityForResult(chooserIntent, REQUEST_IMAGE_CAPTURE); 
} 

获取唯一的文件名的方法:

private static String getUniqueImageFilename() { 
    // TODO Auto-generated method stub 
    String fileName = "img_" + System.currentTimeMillis() + ".jpg"; 
    return fileName; 
} 
+0

画廊和相机都不工作?你能检查两者吗? – berserk 2014-10-28 18:43:43

+0

两个都没有工作。敬酒说相机的“file:// .....”和相册的“content:// ......”。 – 2014-10-28 18:45:37

+0

在相机中,你会得到确切的uri,但是在图库的情况下,你会得到内容Uri。 – berserk 2014-10-28 18:46:28

回答

1

它是通过从文件创建位图并进行设置的替代方法。我还包括从内容uri到实际uri的转换(至发布文件,您需要实际的uri)和图像采样以避免OOM:

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
if (resultCode == RESULT_OK) { 
    if (requestCode == REQUEST_IMAGE_CAPTURE) { 
     final boolean isCamera; 
     if (data == null) { 
      isCamera = true; 
     } else { 
      final String action = data.getAction(); 
      if (action == null) { 
       isCamera = false; 
      } else { 
       isCamera = action 
         .equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
      } 
     } 

     Uri selectedImageUri; 
     if (isCamera) { 
      selectedImageUri = outputFileUri; 
     } else { 
      Uri selectedImage = data.getData(); 
      String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

      Cursor cursor = activity.getContentResolver().query(
        selectedImage, filePathColumn, null, null, null); 
      cursor.moveToFirst(); 
      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      selectedImageUri = cursor.getString(columnIndex); 
      cursor.close(); 
     } 

     ImageButton pic1 = (ImageButton) findViewById(R.id.ibPic1); 
     Toast.makeText(this, "Image saved to:\n" + selectedImageUri, 
       Toast.LENGTH_LONG).show(); 
     //.setImageURI(selectedImageUri); 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(selectedImageUri, options); 
     options.inSampleSize = calculateInSampleSize(options, dpToPx(100), 
       dpToPx(100)); 

     // Decode bitmap with inSampleSize set 
     options.inJustDecodeBounds = false; 
     Bitmap bMapRotate = BitmapFactory.decodeFile(filePath, options); 
     int width = bMapRotate.getWidth(); 
     int height = bMapRotate.getHeight(); 
     if (width > height) 
      para = height; 
     else 
      para = width; 
     if (bMapRotate != null) { 
      pic1.setImageBitmap(bMapRotate); 
     } 
    } 
} 

private int dpToPx(int dp) { 
    float density = activity.getResources().getDisplayMetrics().density; 
    return Math.round((float) dp * density); 
} 

public static int calculateInSampleSize(BitmapFactory.Options options, 
     int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     // Calculate ratios of height and width to requested height and 
     // width 
     final int heightRatio = Math.round((float) height 
       /(float) reqHeight); 
     final int widthRatio = Math.round((float) width/(float) reqWidth); 

     // Choose the smallest ratio as inSampleSize value, this will 
     // guarantee 
     // a final image with both dimensions larger than or equal to the 
     // requested height and width. 
     inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 
    } 

    return inSampleSize; 
} 
+0

这是工作,但不是当我使用相机时,这是我如何得到:outputFileUri = Uri.fromFile(sdImageMainDirectory);我改变了:else if(requestCode == CAMERA_REQUEST && resultCode == -1){file:filePath = outputFileUri;到outputFileUri.toString();此外,我不知道它是否意味着我没有CAMERA_REQUEST代码,因为我从一个意图启动openImageIntent从相机或其他图像库中选择。你想让我发布意向方法吗? – 2014-10-28 20:07:14

+0

@KæmpeKlunker只需要根据你的修改。像你用布尔值来检查相机或画廊,我检查请求代码。 CAMERA_REQUEST只是摄像机requestCode的一个数字。 – berserk 2014-10-28 20:13:43

+0

是的,我知道,但你有RESULT_LOAD_IMAGE和CAMERA_REQUEST,我有:startActivityForResult(chooserIntent,int);所以我不知道如何定义每个数字?您可以先查看我的问题链接“相机和画廊”,看看代码,它是最有争议的答案。 – 2014-10-28 21:18:03