当前位置: 首页 > 知识库问答 >
问题:

Android允许用户从图库或相机中选择/捕捉照片

印宏阔
2023-03-14
    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i,3);
        Uri selectedImage = data.getData();

        filename = "NEWIMAGE";
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        final int REQUIRED_SIZE=70;
        int scale = 1;
        BitmapFactory.Options options = new BitmapFactory.Options();
        if (options.outHeight > REQUIRED_SIZE || options.outWidth > REQUIRED_SIZE) {
            scale = (int)Math.pow(2, (int) Math.round(Math.log(REQUIRED_SIZE / 
               (double) Math.max(options.outHeight, options.outWidth)) / Math.log(0.5)));
        }

        options.inJustDecodeBounds = true;
        options.inSampleSize = scale;           
        photo = BitmapFactory.decodeFile(picturePath, options);
E/AndroidRuntime(21260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=3, result=-1, data=Intent { dat=content://media/external/images/media/2449 }} to activity {com.aquariumzoekenpro.android/com.aquariumzoekenpro.android.LogboekNotitie}: java.lang.NullPointerException
E/AndroidRuntime(21260):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3000)
E/AndroidRuntime(21260):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3043)
E/AndroidRuntime(21260):    at android.app.ActivityThread.access$1100(ActivityThread.java:127)
E/AndroidRuntime(21260):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1188)
E/AndroidRuntime(21260):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(21260):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(21260):    at android.app.ActivityThread.main(ActivityThread.java:4441)
E/AndroidRuntime(21260):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(21260):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(21260):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
E/AndroidRuntime(21260):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
E/AndroidRuntime(21260):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(21260): Caused by: java.lang.NullPointerException
E/AndroidRuntime(21260):    at com.aquariumzoekenpro.android.LogboekNotitie.onActivityResult(LogboekNotitie.java:1483)
E/AndroidRuntime(21260):    at android.app.Activity.dispatchActivityResult(Activity.java:4649)
E/AndroidRuntime(21260):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2996)
E/AndroidRuntime(21260):    ... 11 more
    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);     
    String filename = "NEWIMAGE1";
    imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/"+filename));
    i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(i,2);
String filename = "NEWIMAGE1";
String urifilename = filename + ".jpg";
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/"+urifilename));
this.getContentResolver().notifyChange(imageUri, null);
ContentResolver cr = this.getContentResolver();     
photo = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
W/dalvikvm(21424): threadid=1: thread exiting with uncaught exception (group=0x40abc210)
E/AndroidRuntime(21424): FATAL EXCEPTION: main
E/AndroidRuntime(21424): java.lang.OutOfMemoryError
E/AndroidRuntime(21424):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
E/AndroidRuntime(21424):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499)
E/AndroidRuntime(21424):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:555)
E/AndroidRuntime(21424):    at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:710)
E/AndroidRuntime(21424):    at com.aquariumzoekenpro.android.LogboekNotitie.onActivityResult(LogboekNotitie.java:1429)
E/AndroidRuntime(21424):    at android.app.Activity.dispatchActivityResult(Activity.java:4649)
E/AndroidRuntime(21424):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2996)
E/AndroidRuntime(21424):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2451)
E/AndroidRuntime(21424):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2492)
E/AndroidRuntime(21424):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1997)
E/AndroidRuntime(21424):    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3371)
E/AndroidRuntime(21424):    at android.app.ActivityThread.access$700(ActivityThread.java:127)
E/AndroidRuntime(21424):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1162)
E/AndroidRuntime(21424):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(21424):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(21424):    at android.app.ActivityThread.main(ActivityThread.java:4441)
E/AndroidRuntime(21424):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(21424):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(21424):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
E/AndroidRuntime(21424):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
E/AndroidRuntime(21424):    at dalvik.system.NativeStart.main(Native Method)

先谢谢你,

西蒙

共有1个答案

司寇高洁
2023-03-14

Simon,我从图库中选择了这个:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");

然后这样处理选择:

  mFilename=null;
  mPath=null;

  Uri selectedImage = data.getData();
  final String[] filePathColumn = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
  Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

  // some devices (OS versions return an URI of com.android instead of com.google.android 
  if (selectedImage.toString().startsWith("content://com.android.gallery3d.provider"))  
  {
      // use the com.google provider, not the com.android provider. 
      selectedImage = Uri.parse(selectedImage.toString().replace("com.android.gallery3d","com.google.android.gallery3d"));
  }

  if (cursor != null) {
      cursor.moveToFirst();
      int columnIndex = cursor.getColumnIndex(MediaColumns.DATA);

      // if it is a picasa image on newer devices with OS 3.0 and up
      if (selectedImage.toString().startsWith("content://com.google.android.gallery3d"))
      {
          columnIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);
          if (columnIndex != -1)
          {
              final Uri uriurl = selectedImage;
              // should do this in a background thread, since we are fetching a large image from the web
              mFilename = getGalleryFile(activity, uriurl);
          }
      }
      else
      {
          // it is a regular local image file
          String filePath = cursor.getString(columnIndex);
          cursor.close();
          mFilename = filePath;
      }
  }
  // If it is a picasa image on devices running OS prior to 3.0
  else if (selectedImage != null && selectedImage.toString().length() > 0)
  {
      final Uri uriurl = selectedImage;
      // should do this in a background thread, since we are fetching a large image from the web
      mFilename = getGalleryFile(activity, uriurl);
   }

至于你想要的相机部分,你所做的看起来很好,只是创建位图的内存用完了。您应该使用BitmapFactory.Options设置BitmapFactory::DecodeStream,将传入图像缩放到要在其中显示的视图的大小。

public static String getGalleryFile(Activity activity, Uri url)
{
    String fileName=null;
    File path;

    try {
        // getCameraStoragePath is a function in my activity
        // that returns a location where I'm writing files
        // you could use Environment.getExternalStorageDirectory()
        // or ....
        path = new File(MyTask.getCameraStoragePath());
    } catch (Exception e1) {
        // todo: handle exception
        return null;
    }

    SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
    fileName = "gallery." + timeStampFormat.format(new java.util.Date()) + ".jpg";
    File out = new File(path, fileName);

    try {
        InputStream is = null;
        if (url.toString().startsWith("content://com.google.android.gallery3d"))
        {
            is=activity.getContentResolver().openInputStream(url);
        }
        else
        {
            is=new URL(url.toString()).openStream();
        }

        OutputStream os = new FileOutputStream(out);

        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1)
        {
            os.write(buffer, 0, len);
        }

        os.close();
        return out.getAbsolutePath();
    }
    catch (Exception ex)
    {
        // todo: handle exception
        return null;
    }
}
 类似资料:
  • 编辑:我调试了应用程序,并用初始化了。这消除了错误,但是现在ImageView没有得到更新,但是当我从Gallery中选择image时,它已经更新了。

  • ap.chooseImage(OPTION | count, CALLBACK) 拍照或从手机相册中选择图片。可直接传入一个数字作为 OPTION.count 参数。 OPTION 参数说明 名称 类型 必选 描述 count Number 否 最大可选照片数,默认1张,上限9张 sourceType String Array 否 相册选取或者拍照,默认 ['camera','album'] CA

  • 我必须做一个按钮,将提供从画廊或从相机选择图像。 结果是有效的。如果我从图库中选择,图像查看器将查看它,如果我选择从相机拍照,它也有效。问题是,在我的show FileChooser()方法中,我所有的意图都在同时运行,所以当我从图库中选择时,相机仍然运行。我选择相机,图库也在打开。我认为我应该在切换案例模式下实现我的代码,但我不明白如何做到这一点。请帮助解决我的初学者问题。

  • 有没有一个标准的方法来调用对话框选择从相机或从图库(如内置电话簿或Skype)的图像? 我看了一下这个,但是代码打开了图库,没有建议从相机中选择它。 设备:Samsung Galaxy Tab Android:2.3.3

  • 为什么应用程序在安装过程中不请求使用摄像头的许可? 舱单:

  • 问题内容: 我正在用Swift编写我的第一个iOS应用程序(仅iPhone)。主应用程序视图应允许用户从相册中选择图像。 我找到了以下 ViewController.swift 示例代码: 并具有以下View Controller Scene- 但是,当我启动该应用程序时,仅显示黑屏。我做错了什么?我发现的另一个示例代码是在Objective-C中,这对我没有帮助。 问题答案: 如果只想让用户使用