Android bitmap对象序列化

      由于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进行处理了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值