Compress and Resize the Image
Bitmap compressBitmap(String file, int width, int height) {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) height);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) width);
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
return bitmap;
}
create a new image file in cache memory
public File gettempImagefile(Bitmap bitmap) {
// create a file to write bitmap data
File f = new File(context.getCacheDir() + "imges.jpg");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 90 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
// write the bytes in file
FileOutputStream fos;
try {
fos = new FileOutputStream(f);
fos.write(bitmapdata);
return f;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
How to use / call this methods
File image = gettempImagefile(compressBitmap(imagePath, 250, 250));
No comments:
Post a Comment