Cannot use java.util.Base64 to encode JPG image to string

Viewed 434

I'm using a java.util.Base64 to encode a few images to string to front end. Most PNG images are working, I can convert the Base64 string result back to image using online conversion. But JPG files are corrupted somehow.

I copied my encoded base64 JPG string to online converter, which cannot render an image. Then I downloaded that image to my local. When I try to open that image, the viewer says:

Error interpreting JPEG image file (Not a JPEG file: starts with 0x99 0xaf)

Is there any other way that I can encode JPG image to string and send it to front end so that front end can display this image? Assuming Base64 not working for JPG now.

Online converter says:

The MIME of file was detected as “application/octet-stream”, but the decoder displays it as “image/octet-stream”.

Preview Image Your browser cannot display the file as “image/octet-stream”.

File Info • MIME type: image/octet-stream • Extension: bin • Size: 4 KB • Download: image.bin

private Map<String, String> download(byte[] output) throws IOException, ScriptException {
    try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(output))) {
      ZipEntry zipEntry = zis.getNextEntry();
      byte[] buffer = new byte[4096];
      Map<String, String> mapTable = new HashMap<>();
      int len;
      while (zipEntry != null) {
        String zipEntryName = zipEntry.getName();
        if (zipEntryName != null) {
          if (zipEntryName.endsWith(".png") || zipEntryName.endsWith(".jpg")) {
            String encodeImage = "";
            while ((len = zis.read(buffer)) > 0) {
              encodeImage = java.util.Base64.getEncoder().withoutPadding().encodeToString(buffer);
            }
            mapTable.put(zipEntryName, encodeImage);
          } else {
            StringBuilder sb = new StringBuilder();
            log.info("File Name " + zipEntryName);
            while ((len = zis.read(buffer)) > 0) {
              sb.append(new String(buffer, 0, len));
            }
            String dataStr = sb.toString();
            mapTable.put(zipEntryName, dataStr);
          }
        }
        zipEntry = zis.getNextEntry();
      }
      zis.closeEntry();
      return mapTable;
    } catch (IOException ioe) {
      log.error("IOException {}", ioe);
      throw ioe;
    }
  }
0 Answers
Related