我过去常常像firstName
中的SharedPreferences
一样:
private String filename = "mySharedString";
private SharedPreferences someData;
someData = getSharedPreferences(filename, 0);
Editor editor = someData.edit();
editor.putString("firstName", phoneNumber);
someData.getString("firstName", "NULL");
效果很好。现在我想保存可能为4 MB
的图像的base 64
SharedPreferences
可以保存base 64吗?或者那个尺寸对它来说很大?
答案 0 :(得分:3)
不要这样做。 SharedPreferences
的文件大小为4MB。 SharedPreferences旨在将私有原始数据存储在键值对中,而且肯定不会存储在文件中。对于存储大文件,请使用内部/外部存储,并在数据库中保留Uri
。
答案 1 :(得分:3)
考虑到您的图片位于路径 - > “/sdcard/test.jpg”,请参阅下面的代码
/*Get image into file*/
File image_file = new File("/sdcard/test.jpg");
/*Get absolute path in bitmap*/
Bitmap mBitmap = BitmapFactory.decodeFile(image_file.getAbsolutePath());
/*Instantiate Byte Array Output Stream to compress the bitmap*/
ByteArrayOutputStream bao_stream = new ByteArrayOutputStream();
/*Compress bitmap*/
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
/*Get byteArray from stream*/
byte[] arr_byte_image = bao_stream.toByteArray();
/*Base6e class has a method name encodeToString using which you can get string from byteArray*/
String img_base64_str = Base64.encodeToString(arr_byte_image, 0);`
现在我们有包含base64字符串格式的整个图像的字符串,我们可以轻松地将其存储到SharedPreferences
如果上述代码有任何疑问,请与我们联系。
答案 2 :(得分:2)
尝试此操作以保存在内存中
public void savedImage(byte[] data) {
InputStream in = new ByteArrayInputStream(data);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap preview_bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
preview_bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteArray = stream.toByteArray();
final String newData = Base64.encodeToString(byteArray, 0);
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(new File(
Environment.getExternalStorageDirectory(), "ImageName.jpg"));
outStream.write(byteArray);
outStream.close();
} catch (FileNotFoundException e) {
Log.d("No File", e.getMessage());
} catch (IOException e) {
Log.d("IO Error", e.getMessage());
}
}
答案 3 :(得分:1)
虽然这是个坏主意,但你可以这样做
Bitmap photo=BitmapFactory.decodeResource(getResources(), R.drawable.addphoto);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
and store this string ba1 to your `SharedPreferences`
private String filename = "mySharedString";
private SharedPreferences someData;
someData = getSharedPreferences(filename, 0);
Editor editor = someData.edit();
editor.putString("firstName", phoneNumber);
editor.putString("ImageData", ba1);
editor.commit()
我认为通过这种方式,您可以将图像保存在共享偏好中。