我开始开发我的第一个Android应用程序,并且已经构建了一个处理具有多个图层的图像的应用程序。我能够将项目文件导出为PNG格式的平面版本,但我希望能够保存分层图像以便以后进行编辑(包括应用于某些图层的任何选项,例如基于文本的图层)。
无论如何,我已确保需要写入文件的类是“可序列化”的,但由于android.graphics.Bitmap不可序列化,我遇到了一个障碍。以下代码将Bitmap作为PNG输出到ByteArray,并应在“readObject”中读取它。然而,当代码运行时-我可以验证“imageByteArrayLength”变量与输出的变量相同-但“Bitmap image”始终为空。
非常感谢您的帮助。谢谢阅读。
无论如何,我已确保需要写入文件的类是“可序列化”的,但由于android.graphics.Bitmap不可序列化,我遇到了一个障碍。以下代码将Bitmap作为PNG输出到ByteArray,并应在“readObject”中读取它。然而,当代码运行时-我可以验证“imageByteArrayLength”变量与输出的变量相同-但“Bitmap image”始终为空。
非常感谢您的帮助。谢谢阅读。
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);
}
}