Android从图库中选择图片

时间:2016-12-16 05:44:50

标签: android android-imageview

我从图库中选择了一张图片,现在我想要的是当用户重新打开应用时,图片就在ImageView,请给我一些建议,这是我的代码

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == RESULT_LOAD_IMG && 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]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();

                imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
                SharedPreferences.Editor editor = getSharedPreferences(AppConstants.VERIFICATION, MODE_PRIVATE).edit();
                editor.putString(AppConstants.PROFILEIMAGE, imgDecodableString);
                editor.commit();
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }

3 个答案:

答案 0 :(得分:1)

试试这段代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        if (requestCode == RESULT_LOAD_IMG && 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]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

            imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
            Bitmap bmap = imgView.getDrawingCache();    
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bmap.compress(Bitmap.CompressFormat.PNG, 90, bytes);
            byte[]imagebytes=bytes.toByteArray();
            String encodedImage = Base64.encodeToString(imagebytes, Base64.DEFAULT);
            SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(ProfilePage.this);
            SharedPreferences.Editor edit=shre.edit();
            edit.putString("image_data",encodedImage);
            edit.commit();
        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

添加以下代码以获取共享首选项

 SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
    String previouslyEncodedImage = shre.getString("image_data", "");
    if( !previouslyEncodedImage.equalsIgnoreCase("") ){
        byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
        imgView.setImageBitmap(bitmap);
    }

答案 1 :(得分:0)

使用

    @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                try {
                    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                            && null != data) {
                        InputStream inputStream = getContentResolver()
                                .openInputStream(data.getData());
                    File outFile = new File(getCacheDir(),"tempImage.png");

                   FileOutputStream fileOutputStream = new FileOutputStream(
                            outFile);
                    copyStream(inputStream, fileOutputStream);
                    fileOutputStream.close();
                    inputStream.close();
                        Bitmap bm = BitmapFactory.decodeStream(inputStream);

                        imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
                        imgView.setImageBitmap(bm);
                        SharedPreferences.Editor editor = getSharedPreferences(AppConstants.VERIFICATION, MODE_PRIVATE).edit();
                        editor.putString(AppConstants.PROFILEIMAGE, outFile.getAbsolutePath());
                        editor.commit();
                    } else {
                        Toast.makeText(this, "You haven't picked Image",
                                Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                            .show();
                }

public static void copyStream(InputStream input, OutputStream output)
            throws IOException {

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    }

答案 2 :(得分:0)

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

    // Here we need to check if the activity that was triggers was the Image Gallery.
    // If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
    // If the resultCode is RESULT_OK and there is some data we know that an image was picked.
    if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
        // Let's read picked image data - its URI
        Uri pickedImage = data.getData();
        // Let's read picked image path using content resolver
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

         // Do something with the bitmap


        // At the end remember to close the cursor or you will end with the RuntimeException!
        cursor.close();
    }
}