Reputation: 41
i am having a database like contact contentprovider, in that user can capture the image of the each contact, after capturing, i am encoding the image into base64 and saving into file and updating that image field with the path of the file, and syncing all the contacts to the server if user is online, and as well i am getting all those data from the server whenever required, while i am fetching image from the file i am facing outofmemory exception base64, if me save the image in the database is that resolve the problem?
Upvotes: 1
Views: 1335
Reputation: 9842
Images usually cause OutOfMemoryException in Android specially when you try to encode the whole image.. For that purpose read image data in chunks, then after applying encoding on chunks save chunks in a temp file. When encoding completes, do whatever you want to do with your encoded image file..
Here's the code to encode image from a file and saving it in a file using chunks..
String imagePath = "Your Image Path";
String encodedImagePath = "Path For New Encoded File";
InputStream aInput;
Base64OutputStream imageOut = null;
try {
aInput = new FileInputStream(imagePath);
// carries the data from input to output :
byte[] bucket = new byte[4 * 1024];
FileOutputStream result = new FileOutputStream(encodedImagePath);
imageOut = new Base64OutputStream(result, Base64.NO_WRAP);
int bytesRead = 0;
while (bytesRead != -1) {
// aInput.read() returns -1, 0, or more :
bytesRead = aInput.read(bucket);
if (bytesRead > 0) {
imageOut.write(bucket, 0, bytesRead);
imageOut.flush();
}
imageOut.flush();
imageOut.close();
} catch (Exception ex) {
Log.e(">>", "error", ex);
}
Upvotes: 1