我有一个类 TouchPoint 实现了 Serialized,因为它包含 Bitmap,所以我为该类编写了 writeObject 和 readObject:
private void writeObject(ObjectOutputStream oos) throws IOException {
long t1 = System.currentTimeMillis();
oos.defaultWriteObject();
if(_bmp!=null){
int bytes = _bmp.getWidth()*_bmp.getHeight()*4;
ByteBuffer buffer = ByteBuffer.allocate(bytes);
_bmp.copyPixelsToBuffer(buffer);
byte[] array = buffer.array();
oos.writeObject(array);
}
Log.v("PaintFX","Elapsed Time: "+(System.currentTimeMillis()-t1));
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException{
ois.defaultReadObject();
byte[] data = (byte[]) ois.readObject();
if(data != null && data.length > 0){
_bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
}
}
问题是我得到
SkImageDecoder::Factory 返回 null
那么我该如何解决它呢。我知道可能的解决方案是将 writeObject() 更改为
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
_bmp.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
oos.writeObject(byteStream.toByteArray);
但这种方法慢了近 10 倍以上。
- copyPixelsToBuffer 写入图像约 14 毫秒
- _bmp.compress ~ 160ms
UPDATE发现实际的问题是之后
buffer.array();
所有 byte[] 数组元素为:0
最后我找到了一种让它工作的同时速度更快的方法。我在使用此方法时遇到了两个问题:
- 我还应该传递 Bitmap.Config 参数,否则我无法解码字节数组
- _bmp.compress 和 _bmp.copyPixelsToBuffer 提供不同的数组,因此我无法使用decodeByteArray。
我这样解决了他们
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
if(_bmp!=null){
int bytes = _bmp.getWidth()*_bmp.getHeight()*4;
ByteBuffer buffer = ByteBuffer.allocate(bytes);
_bmp.copyPixelsToBuffer(buffer);
byte[] array = new byte[bytes]; // looks like this is extraneous memory allocation
if (buffer.hasArray()) {
try{
array = buffer.array();
} catch (BufferUnderflowException e) {
e.printStackTrace();
}
}
String configName = _bmp.getConfig().name();
oos.writeObject(array);
oos.writeInt(_bmp.getWidth());
oos.writeInt(_bmp.getHeight());
oos.writeObject(configName);
} else {
oos.writeObject(null);
}
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException{
ois.defaultReadObject();
byte[] data = (byte[]) ois.readObject();
if (data != null) {
int w = ois.readInt();
int h = ois.readInt();
String configName = (String) ois.readObject();
Bitmap.Config configBmp = Bitmap.Config.valueOf(configName);
Bitmap bitmap_tmp = Bitmap.createBitmap(w, h, configBmp);
ByteBuffer buffer = ByteBuffer.wrap(data);
bitmap_tmp.copyPixelsFromBuffer(buffer);
_bmp = bitmap_tmp.copy(configBmp,true);
bitmap_tmp.recycle();
} else {
_bmp = null;
}
}
这对我来说足够快了 - 比 bmp.compress 方式快大约 15 倍。希望这可以帮助 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)