7

I want to save the image without compressing it and want to save it in it's original form i.e. when image is compressed the image size decreases and image become small. I am using native camera for this purpose. I am working in android studio. I am making an app in which i am using a camera to save image. But the image is compressed and is very small and very lower quality.

Below is my code for saving image

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
    if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        if(resultCode == Activity.RESULT_OK)
        {
            Bitmap bmp = (Bitmap)data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            // convert byte array to Bitmap
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

            if(isStoragePermissionGranted())
            {
                SaveImage(bitmap);
            }


        }
    }else {
        switch (requestCode) {
            case 1000:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        // All required changes were successfully made
                        getLocation();
                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(this, "Location Service not Enabled", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                break;
        }

    }


}

private void SaveImage(Bitmap finalBitmap) {

    File storageDir = new File (String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));
    String root = storageDir + Environment.getExternalStorageDirectory().getAbsolutePath().toString();
    Log.v(LOG_TAG, root);
    File myDir = new File(root + "/captured_images");
    if (!myDir .exists())
    {
        myDir .mkdirs();
    }
    Random generator = new Random();
    int n = 1000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(myDir,fname);
    try {
        file.createNewFile();
        MediaScannerConnection.scanFile(getApplicationContext(), new String[]  {file.getPath()} , new String[]{"image/*"}, null);
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

Update 1

For more understanding i am putting my onClick method

   btn_camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Check permission for camera

            if(ActivityCompat.checkSelfPermission(MainActivity.this, CAMERA)
                    != PackageManager.PERMISSION_GRANTED)
            {
                // Check Permissions Now
                // Callback onRequestPermissionsResult interceptado na Activity MainActivity

                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{CAMERA},
                        MainActivity.REQUEST_CAMERA);
            }
            else {


                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );

            }


        }
    });

I searched the solution and found that i can use AndroidBitmapUtil class so i copy and pasted this class into my project i.e. i created a new class. But i don't know how to use it. Although it is described that i can save image by doing new AndroidBmpUtil().save(bmImage, file);. But again i can't match with my code :(

Any help would be highly appreciated

Community
  • 1
  • 1
Moeez
  • 494
  • 9
  • 55
  • 147
  • The camera app saved a big file to .../DCIM/Camera. But you are using and saving a thumbnail of the image. Hence the low quality. You should provide a path to your camera intent where the camera app will save the image. Basic stuff. You are number #### who asks this. – greenapps Feb 28 '17 at 10:49
  • @greenapps kindly see my updated code – Moeez Feb 28 '17 at 11:52

3 Answers3

2

new AndroidBmpUtil().save(source, sdcardBmpPath);

USER ABOVE LINE OF CODE AND FOLLOW BELOW LINK

https://github.com/ultrakain/AndroidBitmapUtil

vijay chhalotre
  • 396
  • 2
  • 11
  • I have figured out some thing and set up the code as per my understanding but when i run the app it doesn't run and gives me error `Error:(39, 30) error: cannot find symbol method getWidth()` , `Error:(40, 31) error: cannot find symbol method getHeight()` , `Error:(62, 18) error: cannot find symbol method getPixels(int[],int,int,int,int,int,int)` These all are in `AndroidBmpUtil` If you know how to solve this issue kindly tell me. I'll try to implement the other method given by you if this one not resolve my issue – Moeez Feb 28 '17 at 10:41
  • Works like a breeze – rlib Jan 17 '23 at 12:20
1

Open Camera and save image into some specific directory.

solution number 1

private String pictureImagePath = "";

private void openBackCamera() {

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

String imageFileName = timeStamp + ".jpg";

File storageDir = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES);

pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;

File file = new File(pictureImagePath);

Uri outputFileUri = Uri.fromFile(file);

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);               

cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

startActivityForResult(cameraIntent, 1);}

Handle Image

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == 1) {
File imgFile = new  File(pictureImagePath);

    if(imgFile.exists()){        

   Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

   ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

   myImage.setImageBitmap(myBitmap);

    }
}

solution number 2

I have used the following code and this works perfectly fine for me.

        values = new ContentValues();

        values.put(MediaStore.Images.Media.TITLE, "New Picture");

        values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");

        imageUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        startActivityForResult(intent, PICTURE_RESULT);

and also

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    switch (requestCode) {

    case PICTURE_RESULT:

        if (requestCode == PICTURE_RESULT)

            if (resultCode == Activity.RESULT_OK) {

                try {

                    thumbnail = MediaStore.Images.Media.getBitmap(

                            getContentResolver(), imageUri);

                    imgView.setImageBitmap(thumbnail);

                    imageurl = getRealPathFromURI(imageUri);    

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }
    }
}

and

public String getRealPathFromURI(Uri contentUri) {

    String[] proj = { MediaStore.Images.Media.DATA };

    Cursor cursor = managedQuery(contentUri, proj, null, null, null);

    int column_index = cursor

            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

    cursor.moveToFirst();

    return cursor.getString(column_index);
}
Moeez
  • 494
  • 9
  • 55
  • 147
vijay chhalotre
  • 396
  • 2
  • 11
  • Values is in string type ? – Moeez Feb 28 '17 at 11:03
  • and i will be using it in `onCreate` method.? – Moeez Feb 28 '17 at 11:08
  • inside onclick method – vijay chhalotre Feb 28 '17 at 11:11
  • yes dear friend..please accept my answer and increase my reputations :-) – vijay chhalotre Feb 28 '17 at 11:13
  • When i am doing `values = new ContentValues()` it's giving me error incompatible types. and my declaration is `String values, imageUri` – Moeez Feb 28 '17 at 11:16
  • replace - ContentValues values; and String imageUri; – vijay chhalotre Feb 28 '17 at 11:20
  • Also facing same error in `imageUri` so i have declared them `ContentValues values; Uri imageUri;` – Moeez Feb 28 '17 at 11:21
  • Also i am not using `imageView` so should i skip this piece of code ? ` thumbnail = MediaStore.Images.Media.getBitmap( getContentResolver(), imageUri); imgView.setImageBitmap(thumbnail)` – Moeez Feb 28 '17 at 11:23
  • I am getting this error while saving the image ` java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example.accurat.application/com.example.accurat.application.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'byte[] android.content.Intent.getByteArrayExtra(java.lang.String)' on a null object reference ` – Moeez Feb 28 '17 at 11:31
1

For opening camera use

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 File f = new File(android.os.Environment.getExternalStorageDirectory(), "imagename.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);

and in your onActivityresult method use

if (requestCode == 1) {
 File f = new File(Environment.getExternalStorageDirectory().toString());
  for (File temp : f.listFiles()) {
   if (temp.getName().equals("imagename.jpg")) {
    f = temp;
     break;
  }
  }
  try {
   Bitmap bitmap;
   BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

       bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);

      yourimageview.setImageBitmap(bitmap);

  } catch (Exception e) {
    e.printStackTrace();
  }
 }
Ramees
  • 68
  • 4
  • 16
  • I am able to open the camera in my `onClick` method i have ` Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );` – Moeez Feb 28 '17 at 11:33
  • ya that is alright...but i am passing file uri also while opening the camera. ie.. the location to save the image .so i guess it will get saved without any compression – Ramees Feb 28 '17 at 11:36
  • i am not using image view so where to pass `bitmap` ? – Moeez Feb 28 '17 at 11:50
  • it is not compalsary to use imageview. you can use that piece of code in onActivityResult method to get image in anywhere in your application to get the image in bitmap format. – Ramees Feb 28 '17 at 11:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/136852/discussion-between-faisal1208-and-ramees). – Moeez Feb 28 '17 at 11:55
  • the link provided in chat doesn't help me out – Moeez Feb 28 '17 at 14:08