我已經開始研究我的第一個android應用程序,並具有處理具有多個圖層的圖像的應用程序的基礎。我能夠將平面版本的項目文件導出爲PNG,但我希望能夠保存分層圖像以供日後編輯(包括應用於某些圖層的任何選項,例如基於文本的圖層)。序列化和反序列化Java中的android.graphics.Bitmap
無論如何,我已經確保需要寫入文件的類是'可序列化的',但是由於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);
}
}
我不認爲這段代碼表示如何正確使用序列化。 – 2016-02-05 22:51:13