Updated 24 September 2023
The camera is the powerful tool and most Android-powered devices already have at least one camera installed. After sparing some time from taking selfies (most important use of camera ever known), we can also use it for many other purposes.
From a seller(E-commerce) point of view, he can add a new product from his application by adding product details and beautiful pictures taken from his camera.
In this post, we are going to take images from the camera and will upload to the PHP web server using multipart connection type.
We will use an existing camera application (that is bundled with all android devices having a camera).
Default  camera app itself gives us the ability to review/retake the image, and once an image is accepted.
1 2 3 4 |
<manifest ... > Â Â <uses-feature android:name="android.hardware.camera" android:required="true" /> Â Â ... </manifest> |
to allow only those devices which contain built-in camera functionality.
As we know from Marshmallow 6.0 Permission policies are changed thus Permissions are requested on runtime.
1 2 |
String[] permissions = {"android.permission.WRITE_EXTERNAL_STORAGE"}; requestPermissions(permissions, RC_PERMISSIONS); |
1 2 3 4 5 6 7 8 9 10 |
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == permsRequestCode) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, REQUEST_CAMERA); } } } |
1 2 |
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, REQUEST_CAMERA); |
Action “android.provider.MediaStore.ACTION_IMAGE_CAPTURE” Â is used to invoke the native Camera of the device.
Now We will Override the onActivitityResultÂ
We will receive a Bitmap of data that we store in a temporary file. This temporary file is uploaded afterwards.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode==REQUEST_CAMERA) { Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes); File destination = new File(Environment.getExternalStorageDirectory(),"temp.jpg"); FileOutputStream fo; try { fo = new FileOutputStream(destination); fo.write(bytes.toByteArray()); fo.close(); } catch (IOException e) { e.printStackTrace(); } new uploadFileToServerTask().execute(destination.getAbsolutePath()); } } |
Notice that the image returned by the camera application is passed as an extra named ‘data’ through to the intent of the calling activity. This ‘data’ is a Bitmap object.
Hot Served uploadFileToServerTask uploads the file to PHP server using multipart connection type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
private class uploadFileToServerTask extends AsyncTask<String, String, Object> { @Override protected String doInBackground(String... args) { try { String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; @SuppressWarnings("PointlessArithmeticExpression") int maxBufferSize = 1 * 1024 * 1024; java.net.URL url = new URL((ApplicationConstant.UPLOAD_IMAGE_URL) + IMAGE + customer_id); Log.d(ApplicationConstant.TAG, "url " + url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs. connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // Set HTTP method to POST. connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); FileInputStream fileInputStream; DataOutputStream outputStream; { outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); String filename = args[0]; outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + filename + "\"" + lineEnd); outputStream.writeBytes(lineEnd); Log.d(ApplicationConstant.TAG, "filename " + filename); fileInputStream = new FileInputStream(filename); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); } int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Log.d("serverResponseCode", "" + serverResponseCode); Log.d("serverResponseMessage", "" + serverResponseMessage); fileInputStream.close(); outputStream.flush(); outputStream.close(); if (serverResponseCode == 200) { return "true"; } } catch (Exception e) { e.printStackTrace(); } return "false"; } @Override protected void onPostExecute(Object result) { } } |
For Further Reading:
http://developer.android.com/reference/android/hardware/Camera.html
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
8 comments
1) You start the camera
2) Take a picture
3) The picture is saved to the gallery
4) The image is uploaded to the server
It consist of calling CAMERA and uploading picture via Multi part request.
Hope this help
1. CaptionBot works well ,but it has an upload picture button , and how to solve it for Android phone automatic uploading captured photo.
2. A great deal is for your helping to the blind.
3. Thanks, Jesus’ s love.