简体   繁体   中英

Android: Saving image from gallery and then loading into imageview

I have an onclick that will allow a user to select a file from gallery like so:

case R.id.ColourCustom:
                customBorderChange();
                break;

private void customBorderChange() {
    final ImageView QPBackground = (ImageView) findViewById(R.id.QPBackground);
    menuHandler.removeCallbacks(menuTimer);
    menuHandler.postDelayed(menuTimer, 5000);
    bgHandler.removeCallbacks(runnableBG);
    bgHandler.postDelayed(runnableBG, 2000);
    Intent i = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, GALLERY_REQUEST);
    File file = getFileStreamPath("QuickPlayBG.png");
    if (file.exists()) {
        QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
    } else {
        String uri21 = "@drawable/bg_green";
        int imageResource21 = getResources().getIdentifier(uri21, null, getPackageName());
        QPBackground.setBackgroundResource(imageResource21);
    }
}

This sends you here:

protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
    Uri selectedImageUri;
    if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && null !=
            data) {
        selectedImageUri = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

        cursor.close();
    }
    try {
        Bundle extras = data.getExtras();
        Bitmap photo = extras.getParcelable("data");
        saveBGFile(photo);
    } catch (Exception e) {
        String errorMessage = "Make your mind up mate!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
    try {
        saveQPConfig();
    } catch (IOException e) {
        String errorMessage = "Saving failed";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

Which saves the file, using saveBGFile:

public void saveBGFile(Bitmap image) {
    FileOutputStream out = null;
    String filename = "QuickPlayBG.png";
    try {
        out = new FileOutputStream(filename);
        image.compress(Bitmap.CompressFormat.PNG, 100, out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The issue is with this line only:

QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));

It doesn't load anything. If I change "QuickPlayBG.png" to another filename that I am using in another part of my app, it loads fine. Both files are created using the same method. I verified that "QuickPlayBG.png" exists.

Compiler gives me the following hint:

E/﹕ ReadStreamToBuffer : Qmage Stream read error!! required length 12 bytes, but red 0 bytes
E/﹕ isQmage : input SkStreamRewindable length is less than Qmage minimum size : 0

I think it has to do with the way I am saving the image, but I cannot see the fault myself. What could be the problem, that it is not loading the image?

Edit:

Here is the getThumbnail method I am using (works for another filename):

public Bitmap getThumbnail(String filename) {
    final Context context = this;
    String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    Bitmap thumbnail = null;

    if (thumbnail == null) {
        try {
            File filePath = context.getFileStreamPath(filename);
            FileInputStream fi = new FileInputStream(filePath);
            thumbnail = BitmapFactory.decodeStream(fi);
        } catch (Exception ex) {
            Log.e("getThumbnail() !exist", ex.getMessage());
        }
    }
    return thumbnail;
}

Use this short and sweet code for this. use intent of gallery.

1.declaire variable.

private static int RESULT_IMG = 1;
String imgString;

2.call intent of gallery on onclick of button.

Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);

3.onActivityResult to your code.

@Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
try {
    if (requestCode == RESULT_IMG && responseCode == RESULT_OK
                    && null != data) {
    Uri pickedImage = data.getData();
    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(pickedImage,
            filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    imgString = cursor.getString(columnIndex);
    cursor.close();

    //set bitmap to your imageview
    ImageView imgView = (ImageView) findViewById(R.id.imgView);
    imgView.setImageBitmap(BitmapFactory.decodeFile(imgString));
} else {
    Toast.makeText(this, "please select picture",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
    Toast.makeText(this, "error message", Toast.LENGTH_LONG)
                    .show();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM