Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress camera image before upload

I am using this code (from www.internetria.com) to take a photo and upload to a server:

onCreate:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri output = Uri.fromFile(new File(foto)); intent.putExtra(MediaStore.EXTRA_OUTPUT, output); startActivityForResult(intent, TAKE_PICTURE); 

onActivityResult:

ImageView iv = (ImageView) findViewById(R.id.imageView1);         iv.setImageBitmap(BitmapFactory.decodeFile(foto));          File file = new File(foto);         if (file.exists()) {             UploaderFoto nuevaTarea = new UploaderFoto();             nuevaTarea.execute(foto);         }         else             Toast.makeText(getApplicationContext(), "No se ha realizado la foto", Toast.LENGTH_SHORT).show(); 

UploaderFoto:

ProgressDialog pDialog; String miFoto = "";  @Override protected Void doInBackground(String... params) {     miFoto = params[0];     try {          HttpClient httpclient = new DefaultHttpClient();         httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);         HttpPost httppost = new HttpPost("http://servidor.com/up.php");         File file = new File(miFoto);         MultipartEntity mpEntity = new MultipartEntity();         ContentBody foto = new FileBody(file, "image/jpeg");         mpEntity.addPart("fotoUp", foto);         httppost.setEntity(mpEntity);         httpclient.execute(httppost);         httpclient.getConnectionManager().shutdown();     } catch (Exception e) {         e.printStackTrace();     }     return null; } 

And I want to compress the image, because the size is too big.

I don't know how to add bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); to my app

like image 816
David Avatar asked Oct 25 '13 15:10

David


People also ask

Can you compress an image without losing quality?

If you want to resize an image without losing quality, you need to make sure that the "Resample" checkbox is unchecked. This checkbox tells Paint to change the number of pixels in the image. When you uncheck this box, Paint will not change the number of pixels, and the quality of the image will not be reduced.


1 Answers

Take a look over here: ByteArrayOutputStream to a FileBody

Something along these lines should work:

replace

File file = new File(miFoto); ContentBody foto = new FileBody(file, "image/jpeg"); 

with

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 file size is still an issue you may want to scale the picture in addition to compressing it.

like image 181
Matthew Wesly Avatar answered Sep 18 '22 20:09

Matthew Wesly