1

My app lets you pick an image from gallery and shows it in imageview, but when you close the activity and open it again the image is not there anymore.

  private final static int RESULT_LOAD_IMAGE = 1;

public void getpic(View view) {
    Intent i = new Intent(
            Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(i, RESULT_LOAD_IMAGE);
}




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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

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

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String selectedimage = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.imageButton3);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageBitmap(BitmapFactory.decodeFile(selectedimage));

    }


}

How can I save the picked image?

Bozhidar
  • 29
  • 4

2 Answers2

0

You can get Bitmap from ImageView to save it:

imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();

OutputStream fOut = null;
Uri outputFileUri;
try {
    File root = new File(Environment.getExternalStorageDirectory()
        + File.separator + "folder_name" + File.separator);
    root.mkdirs();
    File sdImageMainDirectory = new File(root, "myPicName.jpg");
    outputFileUri = Uri.fromFile(sdImageMainDirectory);
    fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
    Toast.makeText(this, "Error occured. Please try again later.",
    Toast.LENGTH_SHORT).show();
}
try {
    bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
    fOut.flush();
    fOut.close();
} catch (Exception e) {
}
RoShan Shan
  • 2,924
  • 1
  • 18
  • 38
0

Use Glide for loading image

add below dependencies in build.gradle(app)

compile 'com.github.bumptech.glide:glide:4.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'

add below code inside your onActivityResult

  Glide
  .with(mContext)
  .load(selectedimage)
  .centerCrop()
  .placeholder(R.color.black)
  .crossFade()
  .into(imageView);

For more details refer https://github.com/bumptech/glide

http://en.proft.me/2016/09/12/load-process-and-cache-image-android-using-glide/

Glide load local image by Uri.

Rissmon Suresh
  • 13,173
  • 5
  • 29
  • 38