0

I am trying to take a photo from android and post it to the server but when I run the app, I can access the camera, take a photo and get a crash after accepting the photo, but the app should convert the image to base64, and send it to the server. Why? (The error is in the line 79:Encode_image class: bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

The crash error is :

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/test123.jpg: open failed: EACCES (Permission denied)
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
              Process: com.example.andrei.sendphotos, PID: 3870
              java.lang.RuntimeException: An error occurred while executing doInBackground()
                  at android.os.AsyncTask$3.done(AsyncTask.java:309)
                  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                  at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                  at java.lang.Thread.run(Thread.java:818)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
                  at com.example.andrei.sendphotos.MainActivity$Encode_image.doInBackground(MainActivity.java:79)
                  at com.example.andrei.sendphotos.MainActivity$Encode_image.doInBackground(MainActivity.java:72)
                  at android.os.AsyncTask$2.call(AsyncTask.java:295)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:237)

Here is my code:

public class MainActivity extends AppCompatActivity {

private Button takePhotoButton;
private String encoded_string, image_name;
private Bitmap bitmap;
private File file;
private Uri file_uri;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    takePhotoButton = (Button) findViewById(R.id.take_photo);
    takePhotoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            getFileUri();
            i.putExtra(MediaStore.EXTRA_OUTPUT, file_uri);
            startActivityForResult(i, 10);
        }
    });
}




private void getFileUri() {
    image_name= "test123.jpg";
    //file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + image_name);
    file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + image_name);
    file_uri = Uri.fromFile(file);
}




@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 10 && resultCode == RESULT_OK){
        new Encode_image().execute();
    }
}


private class Encode_image extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {

        bitmap = BitmapFactory.decodeFile(file_uri.getPath());
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100,  stream);


        //convert stream to byte array
        byte[] array = stream.toByteArray();
        encoded_string = Base64.encodeToString(array, 0);
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        makeRequest();
    }
}

private void makeRequest() {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.1.102/AndroidFileUpload/connection.php",

            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> map = new HashMap<>();
            map.put("encoded_string", encoded_string);
            map.put("image_name", image_name);

            return map;
        }
    };
    requestQueue.add(request);
}

}
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
  • `Caused by: java.lang.NullPointerException:`. Google for NullPointerException. – greenapps Nov 05 '16 at 13:23
  • 1
    `bitmap==null` as `decodeFile()` returned a `null`. This is probably caused by using a big jpg file which would expand to a bitmap that would not fit in memory. Try your code with a small jpg image. – greenapps Nov 05 '16 at 13:25
  • I will check it now –  Nov 05 '16 at 13:26
  • `to take a photo from android and post it to the server`. If you have a jpg image file then it is a very bad idea to make a bitmap out of it, then compressing it to a jpg again, before posting to a server. Better just base64 encode the bytes of the file directly to post/upload to the server. – greenapps Nov 05 '16 at 13:29
  • 1
    why is it a bad idea to convert it firstly to base64 and then to send it as a string and then decode it in php? I would also like to save in database and I thought to save the base64 of it instead of the image –  Nov 05 '16 at 13:30
  • 1
    `why is it a bad idea to convert it firstly to base64`. I did not say that yet. But having not said that yet it indeed is a bad idea to encode content base64 before posting as it increases the data tranfer volume with 30% more bytes. – greenapps Nov 05 '16 at 13:33
  • check this SO Answer: http://stackoverflow.com/a/32723550/3140227 – Vipul Asri Nov 05 '16 at 13:38
  • my path is not null –  Nov 05 '16 at 13:48
  • but my bitmap is null and I don't understand why –  Nov 05 '16 at 14:45
  • 1
    http://stackoverflow.com/questions/3401579/get-filename-and-path-from-uri-from-mediastore Try this one –  Nov 05 '16 at 15:56

2 Answers2

1

The problem may be because you are getting the actual path, but you need the real path

0

have you given the permission for writing to external storage in your app AndroidManifest ?

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

or this one for reading from external storage :

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

or if you are using android 6 or above device you should ask for permission explicitly in your code...

hope this helps

SepJaPro2.4
  • 704
  • 9
  • 19
  • I have this permissions. When i debug the app, I seethat bitmap is null, and this may be the cause of the problem: compressing the null bitmap –  Nov 05 '16 at 14:45