【发布时间】:2011-08-17 19:22:46
【问题描述】:
我已经开始开发我的第一个 android 应用程序,并且拥有处理具有多个层的图像的应用程序的基础。我可以将项目文件的平面版本导出为 PNG,但我希望能够保存分层图像以供以后编辑(包括应用于某些图层的任何选项,例如基于文本的图层)。
无论如何,我已确保需要写入文件的类是“可序列化”的,但由于 android.graphics.Bitmap 不可序列化这一事实而遇到了一些障碍。以下代码实质上将位图作为 PNG 输出到 ByteArray 中,并应将其作为“readObject”的一部分读回。但是,当代码运行时——我可以验证读入的“imageByteArrayLength”变量与输出的变量相同——但“位图图像”始终为空。
任何帮助将不胜感激。感谢阅读。
private String title;
private int width;
private int height;
private Bitmap sourceImage;
private Canvas sourceCanvas;
private Bitmap currentImage;
private Canvas currentCanvas;
private Paint currentPaint;
private void writeObject(ObjectOutputStream out) throws IOException{
out.writeObject(title);
out.writeInt(width);
out.writeInt(height);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
currentImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageByteArray = stream.toByteArray();
int length = imageByteArray.length;
out.writeInt(length);
out.write(imageByteArray);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
this.title = (String)in.readObject();
this.width = in.readInt();
this.height = in.readInt();
int imageByteArrayLength = in.readInt();
byte[] imageByteArray = new byte[imageByteArrayLength];
in.read(imageByteArray, 0, imageByteArrayLength);
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap image = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArrayLength, opt);
sourceImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
currentImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
sourceCanvas = new Canvas(sourceImage);
currentCanvas = new Canvas(currentImage);
currentPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
if ( image != null ) {
sourceCanvas.drawBitmap(image, 0, 0, currentPaint);
}
}
【问题讨论】:
标签: java android serialization