由于BitMap没有实现序列化接口,所以当序列化到本地或者在activity之间序列化传递时,会报异常。
在这里介绍个简单的方法实现序列化BitMap:
可以将bitmap对象转换成byte[],然后再序列化或者传递,相反同样可以把byte[]转换成bitma对象。变相的传递序列化Bitmap。
代码如下:
bitmap对象和byte[]的相互转换
public byte[] getBytes(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
return baos.toByteArray();
}
public Bitmap getBitmap(byte[] data){
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
序列化bitmap对象到本地和发序列化:
public void saveInputTypeEditTextDataToFile(Object object,String fileName){
ObjectOutputStream objectOutputStream = null;
try {
FileOutputStream fileOutputStream = mContext.openFileOutput(fileName,Context.MODE_PRIVATE);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public byte[] readBitmapDataFromFile(String fileName){
ObjectInputStream objectInputStream = null;
try {
FileInputStream fileInputStream = mContext.openFileInput(fileName);
objectInputStream = new ObjectInputStream(fileInputStream);
byte[] editTexts = (byte[]) objectInputStream.readObject();
return editTexts;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally{
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
之后就可以根据你自己的逻辑对bitmap进行处理了。