Problem loading textures from ZIP - BitmapHelper closes file

Started by Promyclon, August 21, 2017, 09:09:12 AM

Previous topic - Next topic

Promyclon

Hi

I'm using jPCT-AE. To load set of bitmaps I made a ZIP fie in raw resource folder. I'ts convenient and more space-efficient to load many textures from a ZipInputStream. When I change the model, i.e. in another flavor of the app it will still work event if I'll have completely different set of textures but the file will have the same name. Unfortunately, whenever I call the first new Texture(InputStream is) iterating through ZipEntries in ZipInputStream, the stream is being closed by the BitmapHelper that decodes the image data. In my opinion this is a bug.  Java's BitmapFactory.decodeStream doesnt't do that. Closing of the stream should be the responsibility of the caller, who opens the stream.

To workaround I found the following solution that works as long as I us textures in .png (and whatever else the BitmapFactory recognizes):


private void loadTexturesFromZip(final int resId) {
        ZipEntry txMetadata;
        TextureManager txMan = TextureManager.getInstance();
        try {
            // try-with-resources closes the file automatically when leaving its scope:
            try (ZipInputStream zipTx = new ZipInputStream(res.openRawResource(resId))) {
                while (null != (txMetadata = zipTx.getNextEntry())) {
                    String txName = txMetadata.getName();
                    if (!txMan.containsTexture(txName)) {
                        Log.d(getClass().getSimpleName(), "Loading tx: " + txName);
                        Bitmap tx = BitmapFactory.decodeStream(zipTx);
                        if (null == tx) {
                            Log.e(getClass().getSimpleName(), "failed, bitmap is null");
                        } else {
                            txMan.addTexture(txName, new Texture(tx));
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(getClass().getCanonicalName(), "Texture loading failed: " + e.toString());
        }
    }

EgonOlsen

I see your point, but I don't consider this to be a bug. Either way, it's nothing that can be changed now without breaking a lot of existing code. I'll look into it and maybe add a constructor variant that doesn't close the stream.