2

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:

Parthiban M
  • 1,104
  • 1
  • 10
  • 30
  • 3
    possible duplicate of [Image Upload using intent](http://stackoverflow.com/questions/32824949/image-upload-using-intent) – Selvin Sep 29 '15 at 10:15
  • answer the question, then you can search whether it is a duplicate or not – Parthiban M Sep 29 '15 at 10:18
  • lol, are you ordering me? you are the bad one ... you are reposting same question ... also you did not do any research ... question was already answered many, many times ... learn how to use google – Selvin Sep 29 '15 at 10:20
  • You dont teach me how to use Google. If you can answer u do it. – Parthiban M Sep 29 '15 at 10:24
  • @Selvin I think this is some what different from the what you mention cause i had same issue and i tried your link answer also finally i found a solution please check my answer below – Dulanga Jan 17 '20 at 12:39
  • @Dulanga it's the same ... It's same user ... it's same question(with few changes) – Selvin Jan 17 '20 at 13:16

3 Answers3

0

use this to display image in 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;
        }
    }
Mustanser Iqbal
  • 5,017
  • 4
  • 18
  • 36
  • Hi, can you explain how and where you are getting the path of the file to decode it to convert it to a base64 string – Parthiban M Sep 29 '15 at 18:36
  • as u can see at the top i get URI from data (Uri selectedImage = data.getData();) and at the end i use (getBitmap(selectedImage.getPath());) function to get the bitmap. – Mustanser Iqbal Sep 30 '15 at 05:32
0

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. See this issue: retrieve absolute path when select image from gallery 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. Unfortunately, most examples still seem to use that method even though it's no longer guaranteed to work.

-1

I hade same problem and found this solution from this github sample 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

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;

}
Dulanga
  • 921
  • 11
  • 23