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?
Asked
Active
Viewed 862 times
-1
-
if you convert image in BASE64 then no need to compress again. You can compress image first then convert in base64 and send as string to other via sms – Divyesh Patel Mar 08 '17 at 10:14
-
You can't send **anything but 160 characters** via *SMS*. You can send files via *MMS*. But *MMS* have a **higher cost** than SMS. About 5 to 10 times more, depending on your operator. Are you really sure you want to use a **costly service**, rather than an *eMail*, which is free of charge?! – Phantômaxx Mar 08 '17 at 10:48
-
Yes, I want to use SMS . – Hashir Tariq Mar 08 '17 at 10:56
-
Did you read my comment above? – Phantômaxx Mar 08 '17 at 14:23
-
1Yeah gave up on the idea thanks anyway :) – Hashir Tariq Mar 08 '17 at 17:20
1 Answers
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