1

The code below is supposed to convert an image to its Base64 string. It works but for TIF, only the first "page" is converted and the succeeding pages/parts are missing.

    BASE64Decoder decoder = new BASE64Decoder();
    byte[] decodedBytes = null;
    File file = new File("newtif.tif");
    try {
        FileOutputStream fop;
        decodedBytes = new BASE64Decoder().decodeBuffer(imageString);
        fop = new FileOutputStream(file);
        fop.write(decodedBytes);
        fop.flush();
        fop.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I got the imageString from an actual multipaged-TIF file and converted it to Base64 using:

        BufferedImage image = ImageIO.read(new File(fileLocation));
        BufferedImage newImg;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ImageIO.write(image, "tif", bos);
        byte[] imageBytes = bos.toByteArray();

        BASE64Encoder encoder = new BASE64Encoder();
        imageString = encoder.encode(imageBytes);

Thank you in advance for your help!

Judah Endymion
  • 67
  • 1
  • 12

2 Answers2

1

You cannot just use ImageIO read method to read all tif images. In the example you are just reading first image, because that is what that API does.

Refer to this: Can't read and write a TIFF image file using Java ImageIO standard library

maslan
  • 2,078
  • 16
  • 34
0

Your encoder is the problem. Its a problem because Java does not support multiple "frames" for gif and tif files.

You need to modify the encoder to emit the base64 string, without passing it through the Java image classes.

This can be done using Files.readAllBytes, this created a byte array directly from a file, and doesn't try to read it as an image.

    byte[] imageBytes = Files.readAllBytes(new File(fileLocation).toPath());
    BASE64Encoder encoder = new BASE64Encoder();
    imageString = encoder.encode(imageBytes);
Ferrybig
  • 18,194
  • 6
  • 57
  • 79