I have to upload image which may be choose from gallery or take by camera. I have done this successfully. But problem is , some time image size is 1MB. So it takes more time to upload to server. I need to resize this image before upload. How to do this?
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
AlertDialog alertDialog1;
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
//img = (ImageView) findViewById(R.id.imageView1);
int nh = (int) ( bmp.getHeight() * (512.0 / bmp.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(bmp, 512, nh, true);
img.setImageBitmap(scaled);
} catch (Exception e) {
// AlertDialog alertDialog1;
alertDialog1 = new AlertDialog.Builder(getActivity()).create();
alertDialog1.setTitle("Message");
alertDialog1.setMessage("bala \t "+e.toString());
alertDialog1.show();
}
}else if (requestCode == 1) {
try {
Uri selectedImageUri = data.getData();
imagePath = getPath(selectedImageUri);
destination = new File(imagePath);
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
//int nh = (int) ( bmp.getHeight() * (512.0 / bmp.getWidth()) );
// Bitmap scaled = Bitmap.createScaledBitmap(bmp, 512, nh, true);
img.setImageBitmap(bmp);
//img.setImageBitmap(bmp);
} catch (Exception e) {
// AlertDialog alertDialog1;
alertDialog1 = new AlertDialog.Builder(getActivity()).create();
alertDialog1.setTitle("Message");
alertDialog1.setMessage("sang\t"+e.toString());
alertDialog1.show();
}
}
else{
}
}
Now, how to resize the image?
To resize image you can use the following function
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
To compress the image
Bitmap bmp = BitmapFactory.decodeFile(miFoto)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With