小编Joh*_*rth的帖子

在Java中序列化和反序列化android.graphics.Bitmap

我已经开始研究我的第一个Android应用程序,并具有处理具有多个图层的图像的应用程序的基础.我能够将项目文件的平面版本导出为PNG,但我希望能够保存分层图像以供以后编辑(包括应用于某些图层的任何选项,例如基于文本的图层).

无论如何,我已经确保需要写入文件的类是'Serializable'但是由于android.graphics.Bitmap不可序列化而导致了一些路障.下面的代码实际上将Bitmap作为PNG输出到ByteArray中,并应作为'readObject'的一部分将其读回.但是,当代码运行时 - 我可以验证读入的'imageByteArrayLength'变量与输出的变量相同 - 但'Bitmap image'始终为null.

任何帮助将不胜感激.谢谢阅读.

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(); …
Run Code Online (Sandbox Code Playgroud)

java serialization android

11
推荐指数
2
解决办法
2万
查看次数

标签 统计

android ×1

java ×1

serialization ×1