How to resize the picture taken on Android? - android

I want to send a picture I took to server with multipart/form-data.
Of course, all the process goes very well.
I get the absolute path of the picture on onActivityResult. I sent it to AsyncTask class to change it into File object. Then, I use FileInputStream to send the picture to server.
Here's my code for sending picture.
MainActivity:
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_OK)
return;
if(requestCode == PICK_FROM_CAMERA){
// uri of selected picture
imageUri = data.getData();
// path of selected picture
Cursor c = this.getContentResolver().query(imageUri, null, null, null, null);
c.moveToNext();
absolutePath = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA));
Glide.with(this).load(imageUri).into(image);
}
}
Asynctask class:
absolutePath is in params[7]
FileInputStream fileInputStream ;
wr.writeBytes("\r\n--" + boundary + "\r\n");
wr.writeBytes("Content-Disposition: form-data; name=\"file1[]\"; " +
"filename=\"image.jpg\"\r\n");
wr.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
fileInputStream = new FileInputStream(params[7]);
When I send the picture, I just send it without resizing.
It takes too much time and data to finish sending.
I want to make the picture smaller when sending to server.
that is, with absolute Path, I want to make smaller picture that can be turned into File object.
Can anyone give me some hint?

You can store your imageFile as Uri variable and then resize your image according to your desired width and height to be compressed.
Bitmap b = BitmapFactory.decodeFile(String.valueOf(fileUri));
Bitmap out = Bitmap.createScaledBitmap(b, IMG_WIDTH, IMG_HEIGHT, false);
FileOutputStream fOut;
try {
fOut = new FileOutputStream(fileUri);
out.compress(Bitmap.CompressFormat.JPEG, 60, fOut);
fOut.flush();
fOut.close();
b.recycle();
out.recycle();
Log.i("Compressing file", String.valueOf(uriFile));
} catch (Exception e) {
Log.e("ErrInCompressingPicture","" + e);
}

You can compress the picture you got before you send to server!
one solution is set inSampleSize directly:
public static Bitmap getImage(String imgPath){
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2;
try {
b=BitmapFactory.decodeFile(imgPath, options);
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
the other solution is set width and height of you want:
public static Bitmap getSmallBitmap(String imgPath,int reWidth,int reHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgPath, options);
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize=0;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imgPath, options);
}

Related

When I take photo it is not shown on the imageView only in Galaxy s4

In my app I have to let the user take photo from camera / choose from gallery .
My code working fine on some device but when I run on Galaxy s4 and taking photo by camera the photo doesnt show on the imageView (choose from gallery -working fine)the problem is just when take photo by camera in Galaxy s4.
I scaled the picture before display it on the imageView.
Here is my code to take the picture:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
this is my code after take photo:
if (requestCode == 1)
{
File f = new File(Environment.getExternalStorageDirectory().toString());
File image_file = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles())
{
if (temp.getName().equals("temp.jpg"))
{
f = temp;
break;
}
}
try
{
Bitmap bitmap;
//BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
//bitmap=decodeFile(f.getAbsolutePath());//Collapse image
//setImageOnBitmap(bitmap);//Set the image on the imageview
BitmapHandler b=new BitmapHandler(getApplicationContext());
bitmap=b.decodeFileAsPath(f.getAbsolutePath(),"camera");
setImageOnBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
}
catch (Exception e)
{
e.printStackTrace();
}
}
this is my function to decode the file of the image:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
I have a similar issue on S4, and this is what solved for me:
mImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
Hope this helps.

resize image with activitytresult

how to resize image with my below code ? the code get image but I didnt how to resize it.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
//file name
filePath = data.getData();
try {
// Bundle extras2 = data.getExtras();
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// imageview.setImageBitmap(bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Intent i = new Intent(this,
AddImage.class);
i.putExtra("image", imageInByte);
startActivity(i);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I read a so queston using this way , but its different then my way
File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
Bitmap b= BitmapFactory.decodeFile(PATH_ORIGINAL_IMAGE);
Bitmap out = Bitmap.createScaledBitmap(b, 320, 480, false);
File file = new File(dir, "resize.png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
b.recycle();
out.recycle();
} catch (Exception e) {}
I would like to suggest you that first set the bitmap image to imageview and apply scale i.e., resize as per your requirement using setScaleType method.
ex:
imageview.setScaleType(ScaleType.CENTER);
(or)
If you want to try in same way then I think this link may be help full.
https://argillander.wordpress.com/2011/11/24/scale-image-into-imageview-then-resize-imageview-to-match-the-image/
To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize to true in your BitmapFactory.Options object. For example, an image with resolution 2048x1536 that is decoded with an inSampleSize of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of ARGB_8888). Here’s a method to calculate a sample size value that is a power of two based on a target width and height:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Taken from here

Android: How do i display this image into a bitmap?

What i'm doing/trying to do, is.
1. Take a photo
2. Save it
3. Load/display it into a Bitmap
Opening the Built in camera application:
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE){
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
}
}
decodeSamoleBitmapFromFile:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
I was hoping for it to load it into a bitmap. If anyone could point me in the right direction that would be very helpful!
In order to display a Bitmap, you'll have to use an ImageView. Once you have both the bitmap and the reference to your ImageView, call ImageView.setImageBitmap(Bitmap) to display your bitmap.

Sampling a bitmap from url

I am trying to reduce the size of bitmap from a url. I saw many posts, but all were about sampling a local file. I want to sample the image at url. Here is my code:
public Bitmap getScaledFromUrl(String url) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1 / 10;
try {
return BitmapFactory.decodeStream((InputStream) new URL(url)
.getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Is this approach correct? I am getting out of memory crashes in my app at this function. Any ideas?
This works. I found it at http://blog.vandzi.com/2013/01/get-scaled-image-from-url-in-android.html . Use the following snippet of code, pass params as you like.
private static Bitmap getScaledBitmapFromUrl(String imageUrl, int requiredWidth, int requiredHeight) throws IOException {
URL url = new URL(imageUrl);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(url.openConnection().getInputStream(), null, options);
options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);
options.inJustDecodeBounds = false;
//don't use same inputstream object as in decodestream above. It will not work because
//decode stream edit input stream. So if you create
//InputStream is =url.openConnection().getInputStream(); and you use this in decodeStream
//above and bellow it will not work!
Bitmap bm = BitmapFactory.decodeStream(url.openConnection().getInputStream(), null, options);
return bm;
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
It's really flexible.. I think you should try it out.
You are using it wrong. You are asking to make the picture 10 times bigger :) You should give the command in normal numbers, not fraction. For example:
final BitmapFactory.Options options2 = new BitmapFactory.Options();
options2.inSampleSize = 8;
b = BitmapFactory.decodeFile(image, options2);
with this configuration you obtain 8 times smaller picture than the original.
UPDATE: To load image from internet add this class to the project and do the following:
ImageLoader loader = new ImageLoader(context);
Bitmap image = loader.getBitmap(URL);

How to reduce picture size?

I want to send photo taken from camera to server. But it's size around 1M and i believe it is two much. Thus i want to reduce size of the photo. Below method which I am using.
saveFile - simply save bitmap to file and return path to it.
calculateInSampleSize returns inSampleSize to adjust photo dementions to chosen.
decodeSampledBitmapFromResource decodes birmap from file and rebuild it with new parameters.
Evrything is nice but seems not working. Dimentions of small3.png are 1240*768*24 and size is still ~1M.
I call it with
photo = saveFile(decodeSampledBitmapFromResource(picturePath,
800, 800),3);
methods
public String saveFile(Bitmap bm,int id) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Mk";
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, "smaller" + id + ".png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file.getPath();
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String path,
int reqWidth, int reqHeight) {
Log.d("path", path);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
Why you are writing the image two times just do it in all one time
What i do
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap myBitmap = BitmapFactory.decodeFile({ImagePath}, options);
FileOutputStream fileOutputStream = new FileOutputStream({ImagePath});
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
myBitmapClose.compress(CompressFormat.JPEG, imageQuality, bos);
if (bos != null) {
bos.flush();
bos.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
It will definitely compress Mind the line
myBitmapClose.compress(CompressFormat.JPEG, imageQuality, bos);
where set imageCompression type CompressFormat.JPEG
Thats my code...I want to reduce the size of image where path is String.
String pics=(arraylist.get(position).getImage());
try{
BitmapFactory.Options op = new BitmapFactory.Options();
op.inJustDecodeBounds = true;
//op.inSampleSize = 20; op.outWidth = 25;
op.outHeight = 35;
bmp = BitmapFactory.decodeFile(pics);
image.setImageBitmap(bmp);
}catch(Exception e) {
}

Categories

Resources