如何使用共享首选项将图像保存到 ImageView
How to Save images to ImageView using Shared Preferences
我有一个 activity 打开另一个 activity 来下载图片。图片返回到我原来的 activity 并停留在 imageView 中。那工作正常。我如何保存图像,以便当用户稍后回来或杀死应用程序时,图像仍然存在。我知道我应该使用共享首选项来获取图像路径而不是保存图像本身,但我只是不知道该怎么做。
主要Activity
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
Button button;
ImageView imageView;
String selectedImagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
imageView=(ImageView) findViewById(R.id.image);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Switch();
return true;
}
});
}
public void Switch(){
imageView = (ImageView) findViewById(R.id.image);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==REQUEST_CODE&&resultCode== Activity.RESULT_OK){
try {
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);
Log.v("roni", filePath);
cursor.close();
if(bitmap != null && !bitmap.isRecycled())
{
bitmap = null;
}
bitmap = BitmapFactory.decodeFile(filePath);
//imageView.setBackgroundResource(0);
imageView.setImageBitmap(bitmap);
} catch (Exception e){
e.printStackTrace();
}
}
}
@Override
protected void onPause() {
super.onPause();
save();
}
public void save() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
SharedPreferences.Editor editor = sp.edit();
editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
}
@Override
protected void onResume() {
super.onResume();
restore();
}
public void restore(){
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
bitmap = BitmapFactory.decodeFile(selectedImagePath);
imageView.setImageBitmap(bitmap);
}
}
查看Activity
public class ViewActivity extends ActionBarActivity {
ImageButton imageViews;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
imageViews = (ImageButton) findViewById(R.id.image);
Intent intent = getIntent();
Uri data = intent.getData();
if (intent.getType().indexOf("image/") != -1)
{
imageViews.setImageURI(data);
}
}
Write 方法将您的位图编码为字符串 base64
public static String encodeToBase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
在这个方法中传递 yourBitmap 就像你喜欢的encodeTobase64
SharedPreferences myPrefrence = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeToBase64(yourBitmap));
editor.commit();
当您想在任何地方显示您的图像时,只需使用 decodeToBase64
方法将其再次转换为 Bitmap
public static Bitmap decodeToBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
这里是再次获取位图的代码
SharedPreferences myPrefrence = getPreferences(MODE_PRIVATE);
String imageS = myPrefrence.getString("imagePreferance", "");
Bitmap imageB;
if(!imageS.equals("")) imageB = decodeToBase64(imageS);
但在我看来,您应该只在共享首选项中保留位图路径。
这是我使用的:
public class AppPrefrances {
protected static AppPrefrances INSTANCE;
private static SharedPreferences prefs;
public static AppPrefrances getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new AppPrefrances();
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
return INSTANCE;
}
public void setPath(String path) {
prefs.edit().putString("path", path).apply();
}
public String getPath() {
return prefs.getString("path", "-1");
}
}
现在在您的 onActivityResult 中:
AppPrefrances.getInstance(getApplicationContext()).setPath(file_path);
然后在 onCreate 中,您检查:
String check= AppPrefrances.getInstance(getApplicationContext()).setPath();
if(check!=null&&!check.equals("-1")){
imageView.setImageUri(Uri.parse(check));
}
#EliaszKubala,it my code.
此处错误:
无法恢复 activity {com.example.thang.sdcardimagesactivity/com.example
@Override
protected void onPause() {
super.onPause();
save();
}
public void save(){
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
SharedPreferences.Editor editor = sp.edit();
editor.putString("ImagePath", "abc");
editor.putString("ImagePath", encodeTobase64(bitmap)); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
}
@Override
protected void onResume() {
super.onResume();
restore();
}
public void restore(){
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "abc");
bitmap = decodeToBase64(selectedImagePath);
imageView.setImageBitmap(bitmap);
}
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
public static Bitmap decodeToBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
我有一个 activity 打开另一个 activity 来下载图片。图片返回到我原来的 activity 并停留在 imageView 中。那工作正常。我如何保存图像,以便当用户稍后回来或杀死应用程序时,图像仍然存在。我知道我应该使用共享首选项来获取图像路径而不是保存图像本身,但我只是不知道该怎么做。
主要Activity
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
Button button;
ImageView imageView;
String selectedImagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
imageView=(ImageView) findViewById(R.id.image);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Switch();
return true;
}
});
}
public void Switch(){
imageView = (ImageView) findViewById(R.id.image);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==REQUEST_CODE&&resultCode== Activity.RESULT_OK){
try {
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);
Log.v("roni", filePath);
cursor.close();
if(bitmap != null && !bitmap.isRecycled())
{
bitmap = null;
}
bitmap = BitmapFactory.decodeFile(filePath);
//imageView.setBackgroundResource(0);
imageView.setImageBitmap(bitmap);
} catch (Exception e){
e.printStackTrace();
}
}
}
@Override
protected void onPause() {
super.onPause();
save();
}
public void save() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
SharedPreferences.Editor editor = sp.edit();
editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
}
@Override
protected void onResume() {
super.onResume();
restore();
}
public void restore(){
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
bitmap = BitmapFactory.decodeFile(selectedImagePath);
imageView.setImageBitmap(bitmap);
}
}
查看Activity
public class ViewActivity extends ActionBarActivity {
ImageButton imageViews;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
imageViews = (ImageButton) findViewById(R.id.image);
Intent intent = getIntent();
Uri data = intent.getData();
if (intent.getType().indexOf("image/") != -1)
{
imageViews.setImageURI(data);
}
}
Write 方法将您的位图编码为字符串 base64
public static String encodeToBase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
在这个方法中传递 yourBitmap 就像你喜欢的encodeTobase64
SharedPreferences myPrefrence = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeToBase64(yourBitmap));
editor.commit();
当您想在任何地方显示您的图像时,只需使用 decodeToBase64
方法将其再次转换为 Bitmap
public static Bitmap decodeToBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
这里是再次获取位图的代码
SharedPreferences myPrefrence = getPreferences(MODE_PRIVATE);
String imageS = myPrefrence.getString("imagePreferance", "");
Bitmap imageB;
if(!imageS.equals("")) imageB = decodeToBase64(imageS);
但在我看来,您应该只在共享首选项中保留位图路径。
这是我使用的:
public class AppPrefrances {
protected static AppPrefrances INSTANCE;
private static SharedPreferences prefs;
public static AppPrefrances getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new AppPrefrances();
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
return INSTANCE;
}
public void setPath(String path) {
prefs.edit().putString("path", path).apply();
}
public String getPath() {
return prefs.getString("path", "-1");
}
}
现在在您的 onActivityResult 中:
AppPrefrances.getInstance(getApplicationContext()).setPath(file_path);
然后在 onCreate 中,您检查:
String check= AppPrefrances.getInstance(getApplicationContext()).setPath();
if(check!=null&&!check.equals("-1")){
imageView.setImageUri(Uri.parse(check));
}
#EliaszKubala,it my code.
此处错误: 无法恢复 activity {com.example.thang.sdcardimagesactivity/com.example
@Override
protected void onPause() {
super.onPause();
save();
}
public void save(){
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
SharedPreferences.Editor editor = sp.edit();
editor.putString("ImagePath", "abc");
editor.putString("ImagePath", encodeTobase64(bitmap)); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
}
@Override
protected void onResume() {
super.onResume();
restore();
}
public void restore(){
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "abc");
bitmap = decodeToBase64(selectedImagePath);
imageView.setImageBitmap(bitmap);
}
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
public static Bitmap decodeToBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}