Phill
Phill

Reputation: 1051

Why are images corrupted in my zip file?

I'm generating a zip file in java containing a mix of text and image files, this works fine on one computer but on another my image files are corrupt (same java version and OS); the resulting file sizes are the same but the image will not open in an image editor/viewer, text files are fine.

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
zos.setMethod(ZipOutputStream.DEFLATED);
addZipEntry(zos, "/forms/images/calendar.gif", "images/calendar.gif");
addZipEntry(zos, "/forms/templ/header.php", "templ/header.php");
zos.close();

private void addZipEntry(ZipOutputStream zos, String resourcePath, String entryName) throws IOException {
    ClassLoader cl = getClass().getClassLoader();
    InputStream is = cl.getResourceAsStream(resourcePath);
    zos.putNextEntry(new ZipEntry(entryName));
    zos.write(IOUtils.toByteArray(is));
    zos.closeEntry();
}

Any ideas why the images are getting corrupted?

Here's a visual binary comparison between a corrupt image and the original.

Upvotes: 0

Views: 1164

Answers (2)

user247702
user247702

Reputation: 24232

It seems the tool you use to extract your ZIP file treats your image as ASCII text, replacing any value higher than or equal to 0x80 as an unknown character, replacing it with a questionmark (0x3F).

Upvotes: 2

user207421
user207421

Reputation: 311054

Any ideas why the images are getting corrupted?

That would depend on what IOUtils.toByteArray(is) does.

Upvotes: 0

Related Questions