简体   繁体   English

从“最近的图像”文件夹中选择图像时,图片路径为空

[英]Picture path is null when selected an Image from the "Recent Images" folder

I'm tyring to upload an image for my application, here when I choose an Image from my Gallery it works fine, now If I select the same image from "Recent" folder the picture path is null and I'm unable to upload the image.我正在为我的应用程序上传一张图片,在这里当我从我的图库中选择一张图片时它工作正常,现在如果我从“最近”文件夹中选择相同的图片,图片路径为空,我无法上传图片。 Can you please help me resolving this issue.你能帮我解决这个问题吗。

Here's my code for your reference:这是我的代码供您参考:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // find the views
    image = (ImageView) findViewById(R.id.uploadImage);
    uploadButton = (Button) findViewById(R.id.uploadButton);
    takeImageButton = (Button) findViewById(R.id.takeImageButton);
    selectImageButton = (Button) findViewById(R.id.selectImageButton);

    selectImageButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            selectImageFromGallery();

        }
    });

    takeImageButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent cameraIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);

            /*
             * Picasso.with(MainActivity.this) .load(link) .into(image);
             */

        }
    });

    // when uploadButton is clicked
    uploadButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // new ImageUploadTask().execute();
            Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT)
                    .show();
            uploadTask();
        }
    });
}

protected void uploadTask() {
    // TODO Auto-generated method stub
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 100, bos);
    byte[] data = bos.toByteArray();
    String file = Base64.encodeToString(data, 0);
    Log.i("base64 string", "base64 string: " + file);
    new ImageUploadTask(file).execute();
}

/**
 * Opens dialog picker, so the user can select image from the gallery. The
 * result is returned in the method <code>onActivityResult()</code>
 */
public void selectImageFromGallery() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),
            PICK_IMAGE);
}

/**
 * Retrives the result returned from selecting image, by invoking the method
 * <code>selectImageFromGallery()</code>
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
            && null != data) {

        Uri selectedImage = data.getData();
        Log.i("selectedImage", "selectedImage: " + selectedImage.toString());
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

        /*
         * Cursor cursor = managedQuery(selectedImage, filePathColumn, null,
         * null, null);
         */

        cursor.moveToFirst();

        // int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        int columnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String picturePath = cursor.getString(columnIndex);
        Log.i("picturePath", "picturePath: " + picturePath);
        cursor.close();

        decodeFile(picturePath);

    }

}


public void decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);

    image.setImageBitmap(bitmap);
}

Here's my log for your reference:这是我的日志供您参考:

use this to display image in ImageView使用它在 ImageView 中显示图像

Uri selectedImage = data.getData();
imgView.setImageUri(selectedImage);

OR use this..或使用这个..

Bitmap reducedSizeBitmap = getBitmap(selectedImage.getPath());
imgView.setImageBitmap(reducedSizeBitmap);

if you want to reduce the image size and also want to get bitmap如果您想减小图像大小并且还想获取位图

   private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Matrix matrix = new Matrix();
            //set image rotation value to 90 degrees in matrix.
            matrix.postRotate(90);
            //supply the original width and height, if you don't want to change the height and width of bitmap.
            b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);

            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

I ran into this same problem.我遇到了同样的问题。 While there are other ways to consume the URI, there is also a way to get the correct path.虽然有其他方法可以使用 URI,但也有一种方法可以获取正确的路径。 See this issue: retrieve absolute path when select image from gallery kitkat android请参阅此问题: 从画廊 kitkat android 中选择图像时检索绝对路径

It's a bit outdated.它有点过时了。 Here's updated code.这是更新的代码。

        Uri originalUri = data.getData();

        final int takeFlags = data.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // Check for the freshest data.
        getContentResolver().takePersistableUriPermission(originalUri, takeFlags);

            /* now extract ID from Uri path using getLastPathSegment() and then split with ":"
            then call get Uri to for Internal storage or External storage for media I have used getUri()
            */
        String id = originalUri.getLastPathSegment().split(":")[1];
        final String[] imageColumns = {MediaStore.Images.Media.DATA};
        final String imageOrderBy = null;

        Uri uri = getUri();
        String filePath = "path";

        Cursor imageCursor = getContentResolver().query(uri, imageColumns,
                MediaStore.Images.Media._ID + "=" + id, null, imageOrderBy);

        if(imageCursor.moveToFirst()) {
            filePath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
        }

private Uri getUri() {
    String state = Environment.getExternalStorageState();
    if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
        return MediaStore.Images.Media.INTERNAL_CONTENT_URI;

    return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}

Make sure you have the read external storage permission.确保您具有读取外部存储权限。 Also, note that the way you have it written worked pre-kitkat.另外,请注意,您编写它的方式在kitkat 之前是有效的。 Unfortunately, most examples still seem to use that method even though it's no longer guaranteed to work.不幸的是,大多数示例似乎仍然使用该方法,即使它不再保证有效。

I hade same problem and found this solution from this github sample https://github.com/maayyaannkk/ImagePicker我遇到了同样的问题,并从这个 github 示例https://github.com/maayyaannkk/ImagePicker找到了这个解决方案

This is the solution for your issue这是您问题的解决方案

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

    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
            && null != data) {

        Uri selectedImage = data.getData();
        String   imageEncoded = getRealPathFromURI(getActivity(), selectedImageUri);
        Bitmap selectedImage = BitmapFactory.decodeFile(imageString);
        image.setImageBitmap(selectedImage);
    }
}

These method use for get image url这些方法用于获取图像 url

public String getRealPathFromURI(Context context, Uri contentUri) {
    OutputStream out;
    File file = new File(getFilename(context));

    try {
        if (file.createNewFile()) {
            InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
            byte[] inputData = getBytes(iStream);
            out = new FileOutputStream(file);
            out.write(inputData);
            out.close();
            return file.getAbsolutePath();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

private byte[] getBytes(InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }
    return byteBuffer.toByteArray();
}

private String getFilename(Context context) {
    File mediaStorageDir = new File(context.getExternalFilesDir(""), "patient_data");
    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        mediaStorageDir.mkdirs();
    }

    String mImageName = "IMG_" + String.valueOf(System.currentTimeMillis()) + ".png";
    return mediaStorageDir.getAbsolutePath() + "/" + mImageName;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从图像中选择的路径显示为空 - Selected path from image showing null 当我从最近选择图像时,图像在 android 中损坏 | 最近的多张图片 - When i select image from recent then image is broken in android | Multiple images from recent getClipData() returning null when a single image is selected when working fine when multiple images are selected - getClipData() returning null when a single image is selected when working fine when multiple images are selected Android - 从设备中选择文件时文件路径为空 - Android - file path getting null when file is selected from device 显示特定文件夹中的图像并打开所选图像 - Show images in specific folder and open selected image 从图库中的最近图像中选择图像时,Android 应用程序崩溃 - Android app getting crash when select image from Recent images from gallery 在Android中使用摄像头:当照片是由摄像头拍摄而未从图库中选择时,为什么Cursor为null? - Working with camera in Android: Why is Cursor null when the picture is taken by camera and not selected from gallery? 所选图像内容正确路径,但光标为空 - Selected Image content the correct path but cursor is null 不从相机拍摄图像时,选择的图像路径保存最后的图像路径 - selected image path save last image path when image not take from camera Android:文件:从文件浏览器的最近部分选择文件时,无法从内容 URI 获取文件路径 - Android: Files: Unable to get file path from content URI when file is selected from RECENT section in file browser
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM