-1

I want to know if it's possible to convert an image to a base64 string and then compress it using GZIP and send it to another android phone via SMS where it is decompressed, decoded and then the image is shown to the user? If yes, then what could be the possible solution?

Micho
  • 3,929
  • 13
  • 37
  • 40
Hashir Tariq
  • 11
  • 10

1 Answers1

0

Yes,The following code will read the bytes from the file, gzip the bytes and encode them to base64. It works on all readable files smaller than 2 GB. The bytes passed in to Base64.encodeBytes will be the same bytes as in the file, so no information is lost (as opposed to the code above, where you convert the data to JPEG format first).

/*
 * imagePath has changed name to path, as the file doesn't have to be an image.
 */
File file = new File(path);
long length = file.length();
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
if(length > Integer.MAX_VALUE) {
    throw new IOException("File must be smaller than 2 GB.");
}
byte[] data = new byte[(int)length];
//Read bytes from file
bis.read(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bis != null)
    try { bis.close(); }
    catch(IOException e) {
     }
}
//Gzip and encode to base64
String base64Str = Base64.encodeBytes(data, Base64.GZIP);

EDIT2: This should decode the base64 String and write the decoded data to a file: //outputPath is the path to the destination file.

//Decode base64 String (automatically detects and decompresses gzip)
byte[] data = Base64.decode(base64str);
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(outputPath);
    //Write data to file
    fos.write(data);
} catch(IOException e) {
    e.printStackTrace();
} finally {
    if(fos != null)
        try { fos.close(); }
        catch(IOException e) {}
}
Bunny
  • 45
  • 1
  • 14
  • Android does not have the option `Base64.encodeBytes` and `Base64.ZIP` . (https://developer.android.com/reference/android/util/Base64.html) – Hashir Tariq Mar 08 '17 at 10:34