尝试将Hasmap String,Bitmap写入文件,然后将其恢复为Hasmap;
Error : java.io.NotSerializableException: android.graphics.Bitmap
Bitmap不是一个Serializable类,所以我怎么能把它放到一个文件中并把它拿回去?
//output file
fos = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator +"blts/"+"list.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(hashmap);
oos.close();
//gethashmap
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + File.separator +"blts/"+ "list.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
HashList = (HashMap<String, Bitmap>)ois.readObject();
ois.close();
答案 0 :(得分:0)
用于序列化
ByteArrayOutputStream stream = new ByteArrayOutputStream();
currentImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
BitmapDataObject bitmapDataObject = new BitmapDataObject();
bitmapDataObject.serializedBitmap = stream.toByteArray();
bitmapDataObject.serializedBitmap = "";//your string value
out.writeObject(bitmapDataObject);
用于反序列化
BitmapDataObject bitmapDataObject = (BitmapDataObject) in.readObject();
Bitmap image = BitmapFactory.decodeByteArray(
bitmapDataObject.imageByteArray, 0,
bitmapDataObject.imageByteArray.length);
Sting value = bitmapDataObject.getValue();
现在您应该创建自定义类而不是使用HashMap
public class BitmapDataObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String value;
byte[] serializedBitmap;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public byte[] getSerializedBitmap() {
return serializedBitmap;
}
public void setSerializedBitmap(byte[] serializedBitmap) {
this.serializedBitmap = serializedBitmap;
}
}
答案 1 :(得分:0)
由于HashMap已经是Serializable,因此无需替换它。只做一个实现Serializable位图的私有类会更方便。
private static class SerializableBitmap implements Serializable {
private static final long serialVersionUID = 0L;
private byte[] _compressedBitmap;
// constructor compresses bitmap into Serializable form
public SerializableBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
_compressedBitmap = stream.toByteArray();
}
// reconstructs Bitmap for actual use
public Bitmap getBitmap() {
Bitmap bitmap = BitmapFactory.decodeByteArray(_compressedBitmap, 0,
_compressedBitmap.length);
return bitmap;
}
}
然后您可以使用HashMap<String,SerializableBitmap>
代替HashMap<String,Bitmap>
。