I am trying to do Capture Image, compress to a file & upload it to my server. But, when I am doing that, my memory size suddenly increases by 60 MB.
I am doing the following approach to get compress image file path. During this process only,memory size increases suddenly & sometimes I am getting out of memory issue also.
public String getScaledPic(String path)
{
Bitmap img;
try {
String filePath =path;;
String folderName = filePath.substring(0, filePath.lastIndexOf("/")+1);
String tmpFileName = (filePath.substring(filePath.lastIndexOf("/")+1)).split("\\.")[0]+"_tmp.jpg";
File from = new File(filePath);
folderName=getActivity().getFilesDir()+"/";
File to = new File(folderName+tmpFileName);
try {
copy(from, to);
compress(folderName+tmpFileName);
} catch (IOException io){
return path;
}
return folderName+tmpFileName;
}
catch(Exception e)
{
return path;
}
}
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public void compress(String comp) {
try {
String path = comp;
BitmapFactory.Options buffer = new BitmapFactory.Options();
Bitmap bmp = BitmapFactory.decodeFile(path, buffer);
if (bmp.getWidth() > 768 && bmp.getHeight() > 768){
float widthCompression = 768.0f/bmp.getWidth();
float heightCompression = 768.0f/bmp.getHeight();
if (widthCompression>=heightCompression)
{
Bitmap resized = Bitmap.createScaledBitmap(bmp,(int)(bmp.getWidth()*widthCompression), (int)(bmp.getHeight()*widthCompression), true);
bmp.recycle();
FileOutputStream out = new FileOutputStream(path);
resized.compress(CompressFormat.JPEG, 100, out);
resized.recycle();
out.flush();
out.close();
}
else
{
Bitmap resized = Bitmap.createScaledBitmap(bmp,(int)(bmp.getWidth()*heightCompression), (int)(bmp.getHeight()*heightCompression), true);
bmp.recycle();
FileOutputStream out = new FileOutputStream(path);
resized.compress(CompressFormat.JPEG, 100, out);
resized.recycle();
out.flush();
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Is there any mistake my approach? Also, from the image, how to handle the memory leaks or heavy memory usage caused by the bitmaps?
Hey I use the following code to reduce the file size.
===================== Add this class ================================
}
============= use this method to resize the image ==================