setImageURI不工作

时间:2014-10-28 18:41:08

标签: java android

当用户从图库中选择照片或使用相机拍照时,我正在尝试设置我的imageButtons图像。问题是我的imageButtons只是更改为空白图像,但我得到的文件目录。我究竟做错了什么?我从这个答案camera & gallery创建了我的ImageIntent和onActivityResult。但这是我的onActivityResult方法:

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);
        }
    }
}

所以我从Toast知道我得到了Uri's。我尝试了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;
}

1 个答案:

答案 0 :(得分:1)

它可以通过从文件创建位图并进行设置来实现。我还包括从内容uri到实际uri的转换(至于post文件,你需要实际的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;
}