【问题标题】:Android get image path from captured imageAndroid从捕获的图像中获取图像路径
【发布时间】:2014-12-16 01:23:11
【问题描述】:

我在尝试从捕获的图像中获取图像路径时遇到了一些问题。当我的相机按钮点击时:

takePickBtn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent cameraIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(Intent.createChooser(cameraIntent, "Select Picture"), REQUEST_IMAGE_CAPTURE);
        }
    });

然后是我尝试将捕获的图像加载到图像视图并获取字符串以将其传递给 Async Http Post 的代码:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == REQUEST_IMAGE_CAPTURE
                && resultCode == RESULT_OK) {               
            final ContentResolver cr = getContentResolver();
            final String[] p1 = new String[] {
                MediaStore.Images.ImageColumns._ID,
                MediaStore.Images.ImageColumns.DATE_TAKEN
                    };
            Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");
            if ( c1.moveToFirst() ) {
            String uristringpic = "content://media/external/images/media/" +c1.getInt(0);
             Uri uri = Uri.parse(uristringpic);
                try {
                  Bitmap bm = android.provider.MediaStore.Images.Media.getBitmap(cr, uri);
                } finally {

                }
                params.put("filename", uristringpic);
            }
        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

}

但是,通过这样做,捕获的图像已经设置为图像视图。但是当我尝试打印 uristringpic 时,它是空的。有什么想法吗?

提前致谢。

【问题讨论】:

    标签: java android uri android-camera-intent


    【解决方案1】:

    也许你应该这样尝试

    Uri photoUri;
    
    takePickBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent cameraIntent = new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                photoUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(Intent.createChooser(cameraIntent, "Select Picture"), REQUEST_IMAGE_CAPTURE);
            }
        });
    

    现在拍摄图像后,您在 photoUri var 中有图像 uri。

    如果您需要真实路径,请使用

    public static String getPathFromMediaUri(@NonNull Context context, @NonNull Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    

    【讨论】:

    • 但我需要将捕获的图像设置为我的图像视图,同时我需要获取一个字符串 imgPath 将其作为参数传递给我的 servlet
    • @Denise 尝试 imgPath = getPathFromMediaUri(photoUri);位图位图 = BitmapFactory.decodeFile(imgPath); ImageView.setImageBitmap(位图);
    • 不,使用这些代码,照片拍摄后图像不会设置为 imgView
    • @Denise 我在之前评论中提供的代码应该在 onActivityResult 中执行
    • 我发布了另一个帖子,消息更清晰:stackoverflow.com/questions/27500870/…帮我看看:)
    【解决方案2】:

    或者您可以在启动相机意图之前插入一个 putExtra uri,一旦用户拍摄这样的照片,图像将被保存在其中

    创建一个类

    public class UriHelper { 
    Context mContext;
    
    public UriHelper(Context context) {
        mContext = context;
    }
    
    // >> CHECK IF SD CARD IS MOUNTED 
    // >> USE environment.getExternalStorageState() 
    
    // 1) GET EXTERNAL STORAGE DIRECTORY 
    // 2) CREATE THE SUBDIRECTORY 
    // 3) CREATE A FILE NAME 
    // 4) CREATE THE FILE AND RETURN ITS URI 
    // >> use uri.fromFile()
    public Uri getFileUri() {
    
        File mediaFile;
        if (isExternalStorageAvailable()) {
            // 1) Get the external storage directory
    
            String appName = mContext.getString(R.string.app_name);
            Log.i(LOGTAG, "app name is " + appName);
            File mediaStorageDir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appName);
    
            // 2) Create our subdirectory
            if (!mediaStorageDir.exists()) {
                Log.i(LOGTAG, "Storage doest not exists");
                if (!mediaStorageDir.mkdirs()) {
                    // Error
                    Log.i(LOGTAG, "passed here");
                    Log.e(LOGTAG, "Failed to create Directory");
                    return null;
                }
            }
            // 3) Create a file name
            // 4) Create the file
    
            Date now = new Date();
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                    Locale.US).format(now);
            String path = mediaStorageDir.getPath() + File.separator;
            Log.i(LOGTAG, "Path is" + path);
            mediaFile = new File(path + "IMG_" + timeStamp + ".jpg");
    
            Log.i(LOGTAG, "Created :" + Uri.fromFile(mediaFile));
            return Uri.fromFile(mediaFile);
        } else
            Log.i(LOGTAG, "STORAGE NOT AVAILABLE");
        return null;
    }
    
    private boolean isExternalStorageAvailable() {
        boolean check = false;
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            check = true;
        }
        return check;
      }
    }
    

    在你的活动中

    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
                            UriHelper ur = new UriHelper( this );
                            mPhotoUri = ur.getFileUri(); 
                            if (mPhotoUri != null) {
                            takePhotoIntent .putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
                                startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO );
                            }else{
                                Toast.makeText( this , "There was an error",    Toast.LENGTH_LONG).show(); 
                            }
    

    那么你可以直接使用 uri 路径来查看活动结果中的 imageview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-18
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      相关资源
      最近更新 更多