如何在Android中的sharedPreferences中存储和检索位图?

发布于 2024-12-03 06:00:42 字数 202 浏览 0 评论 0原文

我是安卓新手。我想将我的位图存储在sharedPreferences 中。谁能告诉我这怎么可能?实际上我的要求是,我从图库中获取图像并从相机中拍照,然后在 ImageView 中设置该位图。这些都工作正常。但是当我单击后退按钮时,所有 ImageView 将为空。

所以我想在我的应用程序中存储该位图。

谁能帮助我吗?我对此非常困惑。

谢谢。

I am new in Android. I want to store my bitmap in sharedPreferences. Can anyone tell me how it will possible? Actually my requirements is, I fetch the image from gallery as well as take picture from camera and I set that Bitmap in my ImageView. These all things work properly. But when I click on back button all ImageView will be empty.

So I want to store that Bitmaps throughout my application.

Can anyone help me? I am very much stuck on this.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

热情消退 2024-12-10 06:00:42

嘿朋友们,我在这里找到了问题的解决方案,我发布了我的代码,以便其他人可以使用这个解决方案..

1)。单击按钮 - 打开相机捕获图像

ContentValues values = new ContentValues();  
values.put(MediaStore.Images.Media.TITLE, fileName);  
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);  

Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);  
startActivityForResult(cameraIntent, CAMERA_REQUEST);

2)。单击按钮 - 打开图库以选择图像

Intent galleryintent = new Intent(Intent.ACTION_GET_CONTENT);
galleryintent.setType("image/*");
startActivityForResult(galleryintent, IMAGE_PICK);

3)。静态变量

private static final int CAMERA_REQUEST = 0; 
    private static final int IMAGE_PICK = 1;

4). onActivityResult

    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        {
            switch(requestCode) 
            { 
                case CAMERA_REQUEST:
                    if(resultCode == RESULT_OK)
                    {
                        String[] projection = { MediaStore.Images.Media.DATA}; 
                        Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null); 
                        int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
                        cursor.moveToFirst(); 
                        String capturedImageFilePath = cursor.getString(column_index_data);
                        Log.d("photos*******"," in camera take int  "+capturedImageFilePath);

                        Bitmap photo_camera = BitmapFactory.decodeFile(capturedImageFilePath, options);

                        if(data != null)
                        {
    img_1.setImageBitmap(photo_camera);
                                prefsEditor.putString(Global.PHOTO_1,capturedImageFilePath);
    }
    }
case IMAGE_PICK:
                if(resultCode == RESULT_OK)
                {  
                    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 filePath = cursor.getString(columnIndex);
                    cursor.close();

//                  Bitmap photo = BitmapFactory.decodeFile(filePath);
                   Bitmap photo_gallery = BitmapFactory.decodeFile(filePath,options);
                   img_1.setImageBitmap(photo_gallery);
                        prefsEditor.putString(Global.PHOTO_1, filePath);
}

}
        prefsEditor.commit();
}

5).在 onDestroy() 中
您必须销毁您设置的所有位图。

@Override
    public void onDestroy()
    {
        super.onDestroy();
        if(photo_camera != null)
        {
            photo_camera.recycle();
        }
        if(photo_gallery != null)
        {
            photo_gallery.recycle();
        }
}

6).当您从sharedPrefences获取数据时,您必须将字符串转换为Bitmap,然后您可以在ImageView中设置位图。
例如,Bitmap bit1 = BitmapFactory.decodeFile(strimg1);
然后设置,imageView.setImageBitmap

Hey friends I got the solution of my problem here I post my code so that others can use this solution..

1). on button click - open camera for captureing image

ContentValues values = new ContentValues();  
values.put(MediaStore.Images.Media.TITLE, fileName);  
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);  

Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);  
startActivityForResult(cameraIntent, CAMERA_REQUEST);

2). on button cllick - open Gallery for select image

Intent galleryintent = new Intent(Intent.ACTION_GET_CONTENT);
galleryintent.setType("image/*");
startActivityForResult(galleryintent, IMAGE_PICK);

3). Static variables

private static final int CAMERA_REQUEST = 0; 
    private static final int IMAGE_PICK = 1;

4). onActivityResult

    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        {
            switch(requestCode) 
            { 
                case CAMERA_REQUEST:
                    if(resultCode == RESULT_OK)
                    {
                        String[] projection = { MediaStore.Images.Media.DATA}; 
                        Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null); 
                        int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
                        cursor.moveToFirst(); 
                        String capturedImageFilePath = cursor.getString(column_index_data);
                        Log.d("photos*******"," in camera take int  "+capturedImageFilePath);

                        Bitmap photo_camera = BitmapFactory.decodeFile(capturedImageFilePath, options);

                        if(data != null)
                        {
    img_1.setImageBitmap(photo_camera);
                                prefsEditor.putString(Global.PHOTO_1,capturedImageFilePath);
    }
    }
case IMAGE_PICK:
                if(resultCode == RESULT_OK)
                {  
                    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 filePath = cursor.getString(columnIndex);
                    cursor.close();

//                  Bitmap photo = BitmapFactory.decodeFile(filePath);
                   Bitmap photo_gallery = BitmapFactory.decodeFile(filePath,options);
                   img_1.setImageBitmap(photo_gallery);
                        prefsEditor.putString(Global.PHOTO_1, filePath);
}

}
        prefsEditor.commit();
}

5). in onDestroy()
You have to destroy all bitmap which you setted.

@Override
    public void onDestroy()
    {
        super.onDestroy();
        if(photo_camera != null)
        {
            photo_camera.recycle();
        }
        if(photo_gallery != null)
        {
            photo_gallery.recycle();
        }
}

6). At the time when you fetch data from sharedPrefrences you have to convert string in to Bitmap and then you can set bitmap in ImageView.
for example, Bitmap bit1 = BitmapFactory.decodeFile(strimg1);
and then set , imageView.setImageBitmap

溇涏 2024-12-10 06:00:42

不要将位图存储在共享首选项中。如果您需要在应用程序的生命周期内保留它,可以将其分配给static字段。如果您希望在设备重新启动后仍保留它,请将其放入文件或数据库中。

有关更多信息,请阅读 http://developer.android.com/resources/faq/框架.html#3

Don't store bitmaps in a sharedpreference. If you need to persist it during the lifetime of your application, you can assign it to a static field. If you want to persist it even across device reboots, put it in a file or on the database.

For more information, read http://developer.android.com/resources/faq/framework.html#3

青芜 2024-12-10 06:00:42

假设位图图像为 bitmapImg,您可以将位图图像转换为如下所示的 base64String 后存储

SharedPreferences mSharedPreferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmapImg.compress(Bitmap.CompressFormat.JPEG, 100, baos);

byte[] compressImage = baos.toByteArray();
String sEncodedImage = Base64.encodeToString(compressImage, Base64.DEFAULT);

mSharedPreferences.edit().putString("keyStoredImage",sEncodedImage);
mSharedPreferences.edit().commit();

并从 SharedPreference 中检索存储的图像,如下所示

if(mSharedPreferences.contains("keyStoredImage"))
{

String encodedImage = mSharedPreferences.getString("keyStoredImage",null);

byte[] b = Base64.decode(encodedImage, Base64.DEFAULT);

Bitmap bitmapImage = BitmapFactory.decodeByteArray(b, 0, b.length);
}

Let's say the bitmap image as bitmapImg, you can store the bitmap image after converting into a base64String like the below

SharedPreferences mSharedPreferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmapImg.compress(Bitmap.CompressFormat.JPEG, 100, baos);

byte[] compressImage = baos.toByteArray();
String sEncodedImage = Base64.encodeToString(compressImage, Base64.DEFAULT);

mSharedPreferences.edit().putString("keyStoredImage",sEncodedImage);
mSharedPreferences.edit().commit();

And retrieve the Stored Image from the SharedPreference like the below

if(mSharedPreferences.contains("keyStoredImage"))
{

String encodedImage = mSharedPreferences.getString("keyStoredImage",null);

byte[] b = Base64.decode(encodedImage, Base64.DEFAULT);

Bitmap bitmapImage = BitmapFactory.decodeByteArray(b, 0, b.length);
}
你是年少的欢喜 2024-12-10 06:00:42

您可以像这样在 SharedPreference 中添加值:

SharedPreferences pref = getSharedPreferences("abc", 0);
Editor edit = pref.edit();
edit.putBoolean(arg0, arg1);
edit.putFloat(arg0, arg1);
edit.putInt(arg0, arg1);
edit.putLong(arg0, arg1);
edit.putString(arg0, arg1);
edit.commit();

您只能在 SharedPreference 中添加 Boolean、Float、Int、Long、String 值。

要存储图像,您应该使用设备的外部或内部存储器。

You can add values in SharedPreference like this:

SharedPreferences pref = getSharedPreferences("abc", 0);
Editor edit = pref.edit();
edit.putBoolean(arg0, arg1);
edit.putFloat(arg0, arg1);
edit.putInt(arg0, arg1);
edit.putLong(arg0, arg1);
edit.putString(arg0, arg1);
edit.commit();

You can add only Boolean, Float, Int, Long, String values in SharedPreference.

To store image you should external or internal memory of device.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文