2012-07-31 79 views
18

如果我想捕捉从本机摄像头的图像,我可以这样做:Android的我怎么能说相机或画廊意图一起

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
     intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); 
     startActivityForResult(intent, IMAGE_CAPTURE); 

如果我想从画廊的形象,我可以这样做:

Intent intent = new Intent(); 
       intent.setType("image/*"); 
       intent.setAction(Intent.ACTION_GET_CONTENT); 
       startActivityForResult(Intent.createChooser(intent, 
         "Select Picture"), SELECT_PICTURE); 

我想知道如何把上述两个放在一起。
就意味着得到映像从画廊或捕捉PHOTO Select an action

是否有任何示例代码做呢? 谢谢。

回答

40

如果你想拍照从CameraGallery意图一起,然后检查下面的链接。同样的问题也发布在这里。

Capturing image from gallery & camera in android

更新的代码:下面的代码

检查,在此代码不一样的,你要进入列表视图,但它给在对话框中选择从GALLARY或相机选择图像。

public class UploadImageActivity extends Activity { 
ImageView img_logo; 
protected static final int CAMERA_REQUEST = 0; 
protected static final int GALLERY_PICTURE = 1; 
private Intent pictureActionIntent = null; 
Bitmap bitmap; 

    String selectedImagePath; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main1); 

    img_logo= (ImageView) findViewById(R.id.imageView1); 
    img_logo.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      startDialog(); 
     } 

    }); 
} 

private void startDialog() { 
    AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
      getActivity()); 
    myAlertDialog.setTitle("Upload Pictures Option"); 
    myAlertDialog.setMessage("How do you want to set your picture?"); 

    myAlertDialog.setPositiveButton("Gallery", 
      new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface arg0, int arg1) { 
        Intent pictureActionIntent = null; 

        pictureActionIntent = new Intent(
          Intent.ACTION_PICK, 
          android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
        startActivityForResult(
          pictureActionIntent, 
          GALLERY_PICTURE); 

       } 
      }); 

    myAlertDialog.setNegativeButton("Camera", 
      new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface arg0, int arg1) { 

        Intent intent = new Intent(
          MediaStore.ACTION_IMAGE_CAPTURE); 
        File f = new File(android.os.Environment 
          .getExternalStorageDirectory(), "temp.jpg"); 
        intent.putExtra(MediaStore.EXTRA_OUTPUT, 
          Uri.fromFile(f)); 

        startActivityForResult(intent, 
          CAMERA_REQUEST); 

       } 
      }); 
    myAlertDialog.show(); 
} 

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

    super.onActivityResult(requestCode, resultCode, data); 

    bitmap = null; 
    selectedImagePath = null; 

    if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) { 

     File f = new File(Environment.getExternalStorageDirectory() 
       .toString()); 
     for (File temp : f.listFiles()) { 
      if (temp.getName().equals("temp.jpg")) { 
       f = temp; 
       break; 
      } 
     } 

     if (!f.exists()) { 

      Toast.makeText(getBaseContext(), 

      "Error while capturing image", Toast.LENGTH_LONG) 

      .show(); 

      return; 

     } 

     try { 

      bitmap = BitmapFactory.decodeFile(f.getAbsolutePath()); 

      bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true); 

      int rotate = 0; 
      try { 
       ExifInterface exif = new ExifInterface(f.getAbsolutePath()); 
       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(); 
      } 
      Matrix matrix = new Matrix(); 
      matrix.postRotate(rotate); 
      bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), 
        bitmap.getHeight(), matrix, true); 



      img_logo.setImageBitmap(bitmap); 
      //storeImageTosdCard(bitmap); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } else if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) { 
     if (data != null) { 

      Uri selectedImage = data.getData(); 
      String[] filePath = { MediaStore.Images.Media.DATA }; 
      Cursor c = getContentResolver().query(selectedImage, filePath, 
        null, null, null); 
      c.moveToFirst(); 
      int columnIndex = c.getColumnIndex(filePath[0]); 
      selectedImagePath = c.getString(columnIndex); 
      c.close(); 

      if (selectedImagePath != null) { 
       txt_image_path.setText(selectedImagePath); 
      } 

      bitmap = BitmapFactory.decodeFile(selectedImagePath); // load 
      // preview image 
      bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, false); 



      img_logo.setImageBitmap(bitmap); 

     } else { 
      Toast.makeText(getApplicationContext(), "Cancelled", 
        Toast.LENGTH_SHORT).show(); 
     } 
    } 

} 


} 

另外补充pemission:

<uses-permission android:name="android.permission.CAMERA" /> 

<uses-feature 
    android:name="android.hardware.camera.autofocus" 
    android:required="false" /> 
<uses-feature 
    android:name="android.hardware.camera" 
    android:required="false" /> 

店面形象到SD卡:

private void storeImageTosdCard(Bitmap processedBitmap) { 
    try { 
     // TODO Auto-generated method stub 

     OutputStream output; 
     // Find the SD Card path 
     File filepath = Environment.getExternalStorageDirectory(); 
     // Create a new folder in SD Card 
     File dir = new File(filepath.getAbsolutePath() + "/appName/"); 
     dir.mkdirs(); 

     String imge_name = "appName" + System.currentTimeMillis() 
       + ".jpg"; 
     // Create a name for the saved image 
     File file = new File(dir, imge_name); 
     if (file.exists()) { 
      file.delete(); 
      file.createNewFile(); 
     } else { 
      file.createNewFile(); 

     } 

     try { 

      output = new FileOutputStream(file); 

      // Compress into png format image from 0% - 100% 
      processedBitmap 
        .compress(Bitmap.CompressFormat.PNG, 100, output); 
      output.flush(); 
      output.close(); 

      int file_size = Integer 
        .parseInt(String.valueOf(file.length()/1024)); 
      System.out.println("size ===>>> " + file_size); 
      System.out.println("file.length() ===>>> " + file.length()); 

      selectedImagePath = file.getAbsolutePath(); 



     } 

     catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 
+2

似乎没有答案 – jjLin 2012-07-31 04:16:36

+0

检查我编辑的代码。在这里给出了选择对话框中的选项从gallary/camera选择图像。 – 2012-07-31 04:31:16

+1

你很棒。但是你有没有发现一个问题。从画廊中选择时,选择照片后,imageview中显示的图像将旋转90度?我不知道这是我的设备问题还是其他问题?您可以帮助检查吗? – jjLin 2012-07-31 04:57:20

1

在您的XML布局中创建一个按钮并添加属性android:onClick="takeAPicture" 然后在您的主要活动中创建一个与onClick属性具有相同名称的方法。

public void takeAPicture(View view){ 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
     intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); 
     startActivityForResult(intent, IMAGE_CAPTURE); 
} 

而就做,当你想从库中获得图像的另一种方法:

public void getImageFromGallery(View view) { 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     intent.setType("image/*"); 
     intent.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(Intent.createChooser(intent, 
        "Select Picture"), SELECT_PICTURE); 
} 
+0

我希望把它们放在一起就像上面的截图可以 – jjLin 2012-07-31 04:16:21

+0

您刚刚创建,使用图像按钮? – 0gravity 2012-07-31 04:25:38

1

我想我以前也遇到过你的情况。一个想法是,我们将创建一个带有可选项目的单项清单提醒对话框,并且每个项目将执行由您自己的意图定义的独特功能。如果您需要项目列表中每个元素的图标,则需要做更多工作。希望它会有帮助。

String title = "Open Photo"; 
    CharSequence[] itemlist ={"Take a Photo", 
        "Pick from Gallery", 
        "Open from File"}; 

    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setIcon(R.drawable.icon_app); 
    builder.setTitle(title); 
    builder.setItems(itemlist, new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      switch (which) { 
      case 0:// Take Photo 
       // Do Take Photo task here 
       break; 
      case 1:// Choose Existing Photo 
       // Do Pick Photo task here 
       break; 
      case 2:// Choose Existing File 
       // Do Pick file here 
       break; 
      default: 
       break; 
      } 
     } 
    }); 
    AlertDialog alert = builder.create(); 
    alert.setCancelable(true); 
    alert.show(); 
8

如果你想显示安装在可以处理照片,例如相机,图库,Dropbox的手机中的所有应用程序,等等。

你可以这样做:

1。 - 询问所有可用的意图:

Intent camIntent = new Intent("android.media.action.IMAGE_CAPTURE"); 
    Intent gallIntent=new Intent(Intent.ACTION_GET_CONTENT); 
    gallIntent.setType("image/*"); 

    // look for available intents 
    List<ResolveInfo> info=new ArrayList<ResolveInfo>(); 
    List<Intent> yourIntentsList = new ArrayList<Intent>(); 
    PackageManager packageManager = context.getPackageManager(); 
    List<ResolveInfo> listCam = packageManager.queryIntentActivities(camIntent, 0); 
    for (ResolveInfo res : listCam) { 
     final Intent finalIntent = new Intent(camIntent); 
     finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); 
     yourIntentsList.add(finalIntent); 
     info.add(res); 
    } 
    List<ResolveInfo> listGall = packageManager.queryIntentActivities(gallIntent, 0); 
    for (ResolveInfo res : listGall) { 
     final Intent finalIntent = new Intent(gallIntent); 
     finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); 
     yourIntentsList.add(finalIntent); 
     info.add(res); 
    } 

2。 - 显示自定义对话框,项目列表:

AlertDialog.Builder dialog = new AlertDialog.Builder(context); 
    dialog.setTitle(context.getResources().getString(R.string.select_an_action)); 
    dialog.setAdapter(buildAdapter(context, activitiesInfo), 
      new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int id) { 
        Intent intent = intents.get(id); 
        context.startActivityForResult(intent,1); 
       } 
      }); 

    dialog.setNeutralButton(context.getResources().getString(R.string.cancel), 
      new android.content.DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.dismiss(); 
       } 
      }); 
    dialog.show(); 

这是一个完整的例子:https://gist.github.com/felixgborrego/7943560

+0

做得好@Felix!我有一个问题,我怎么能从一个片段调用这个静态方法?问题是onActivityResult在活动中被触发。 – 2016-02-21 12:30:17

1

您可以使用IntentMapnip的意图合并到一起,并将其展示给用户。

List<ResolveIntent> resolveIntentList = mergeIntents(this, MediaIntents.newSelectPictureIntent(), MediaIntents.cameraIntent()); 
LaunchIntent.withButtomSheetAsList(this, resolveIntentList, "launch using", new ResolvedIntentListener<ResolveIntent>() { 
      @Override 
      public void onIntentSelected(ResolveIntent resolveIntent) { 

      } 
     }); 

您可以在一次调用中合并尽可能多的意图。

+0

不错的图书馆!谢谢 – ClayHerendeen 2017-01-13 19:23:06

0

public static Intent getPickImageIntent(Context context) { 
 
    Intent chooserIntent = null; 
 

 
    List<Intent> intentList = new ArrayList<>(); 
 

 
    Intent pickIntent = new Intent(Intent.ACTION_PICK, 
 
      android.provider.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 = addIntentsToList(context, intentList, pickIntent); 
 
    intentList = addIntentsToList(context, intentList, takePhotoIntent); 
 

 
    if (intentList.size() > 0) { 
 
     chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1), 
 
       context.getString(R.string.pick_image_intent_text)); 
 
     chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{})); 
 
    } 
 

 
    return chooserIntent; 
 
} 
 

 
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) { 
 
    List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0); 
 
    for (ResolveInfo resolveInfo : resInfo) { 
 
     String packageName = resolveInfo.activityInfo.packageName; 
 
     Intent targetedIntent = new Intent(intent); 
 
     targetedIntent.setPackage(packageName); 
 
     list.add(targetedIntent); 
 
    } 
 
    return list; 
 
}