Created
November 25, 2014 09:31
-
-
Save devniel/9ac06f7645546661d9ce to your computer and use it in GitHub Desktop.
Capture photo with android and upload it to SoftLayer Open Storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.devniel.braph.activities; | |
| import android.app.Activity; | |
| import android.net.Uri; | |
| import android.os.Bundle; | |
| import android.view.Menu; | |
| import android.view.MenuItem; | |
| import com.devniel.braph.R; | |
| import com.devniel.braph.fragments.PhotoFragment; | |
| public class AppActivity extends Activity | |
| implements PhotoFragment.OnFragmentInteractionListener { | |
| @Override | |
| protected void onCreate(Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| setContentView(R.layout.activity_app); | |
| if (savedInstanceState == null) { | |
| getFragmentManager().beginTransaction().add(R.id.container, new PhotoFragment()).commit(); | |
| } | |
| } | |
| @Override | |
| public boolean onCreateOptionsMenu(Menu menu) { | |
| // Inflate the menu; this adds items to the action bar if it is present. | |
| getMenuInflater().inflate(R.menu.menu_app, menu); | |
| return true; | |
| } | |
| @Override | |
| public boolean onOptionsItemSelected(MenuItem item) { | |
| // Handle action bar item clicks here. The action bar will | |
| // automatically handle clicks on the Home/Up button, so long | |
| // as you specify a parent activity in AndroidManifest.xml. | |
| int id = item.getItemId(); | |
| //noinspection SimplifiableIfStatement | |
| if (id == R.id.action_settings) { | |
| return true; | |
| } | |
| return super.onOptionsItemSelected(item); | |
| } | |
| @Override | |
| public void onPhoto(Uri uri) { | |
| // Work with photo result here , after upload. | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| apply plugin: 'com.android.application' | |
| android { | |
| compileSdkVersion 21 | |
| buildToolsVersion "21.0.2" | |
| defaultConfig { | |
| applicationId "com.devniel.braph" | |
| minSdkVersion 15 | |
| targetSdkVersion 21 | |
| versionCode 1 | |
| versionName "1.0" | |
| } | |
| buildTypes { | |
| release { | |
| runProguard false | |
| proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' | |
| } | |
| } | |
| } | |
| dependencies { | |
| compile fileTree(dir: 'libs', include: ['*.jar']) | |
| compile "org.apache.httpcomponents:httpclient:4.3.6" | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
| xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" | |
| android:layout_height="match_parent" | |
| tools:context="com.devniel.braph.fragments.PhotoFragment" | |
| android:paddingLeft="@dimen/activity_horizontal_margin" | |
| android:paddingRight="@dimen/activity_horizontal_margin" | |
| android:paddingTop="@dimen/activity_vertical_margin" | |
| android:paddingBottom="@dimen/activity_vertical_margin" | |
| > | |
| <LinearLayout | |
| android:layout_width="fill_parent" | |
| android:layout_height="fill_parent" | |
| android:orientation="vertical"> | |
| <Button | |
| android:id="@+id/btn_take_photo" | |
| android:layout_width="fill_parent" | |
| android:layout_height="100dp" | |
| android:text="@string/take_photo"/> | |
| <Button | |
| android:id="@+id/btn_upload_photo" | |
| android:layout_width="fill_parent" | |
| android:layout_height="100dp" | |
| android:text="@string/upload_photo"/> | |
| <ImageView | |
| android:layout_height="400dp" | |
| android:layout_width="fill_parent" | |
| android:visibility="visible" | |
| android:id="@+id/photo" | |
| android:layout_marginTop="30dp"/> | |
| </LinearLayout> | |
| </FrameLayout> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.devniel.braph.utils; | |
| import android.os.AsyncTask; | |
| import android.util.Log; | |
| import android.view.View; | |
| import android.widget.LinearLayout; | |
| import com.devniel.braph.listeners.HttpResponseListener; | |
| import org.apache.http.HttpResponse; | |
| import org.apache.http.NameValuePair; | |
| import org.apache.http.client.ClientProtocolException; | |
| import org.apache.http.client.methods.HttpPut; | |
| import org.apache.http.entity.FileEntity; | |
| import org.apache.http.impl.client.DefaultHttpClient; | |
| import org.json.JSONException; | |
| import org.json.JSONObject; | |
| import java.io.File; | |
| import java.io.IOException; | |
| import java.net.ConnectException; | |
| import java.net.SocketTimeoutException; | |
| import java.util.ArrayList; | |
| public class HttpFileUploader extends AsyncTask<Object, Void, Object>{ | |
| static final String TAG = HttpJSON.class.getSimpleName(); | |
| public String result; | |
| public HttpResponseListener responseListener; | |
| public LinearLayout progressBar; | |
| public String url; | |
| public String method; | |
| private ArrayList <NameValuePair> headers; | |
| private ArrayList<NameValuePair> postParams; | |
| private int timeout = 30000; | |
| private String filePath; | |
| private String fileType; | |
| public String getFileType() { | |
| return fileType; | |
| } | |
| public void setFileType(String fileType) { | |
| this.fileType = fileType; | |
| } | |
| public String getFilePath() { | |
| return filePath; | |
| } | |
| public void setFilePath(String filePath) { | |
| this.filePath = filePath; | |
| } | |
| public int getTimeout() { | |
| return timeout; | |
| } | |
| public void setTimeout(int timeout) { | |
| this.timeout = timeout; | |
| } | |
| private String authToken; | |
| public String getAuthToken() { | |
| return authToken; | |
| } | |
| public void setAuthToken(String authToken) { | |
| this.authToken = authToken; | |
| } | |
| public HttpFileUploader(String url) { | |
| this.url = url; | |
| this.headers = new ArrayList<NameValuePair>(); | |
| this.postParams = new ArrayList<NameValuePair>(); | |
| } | |
| public HttpFileUploader() { | |
| this.headers = new ArrayList<NameValuePair>(); | |
| this.postParams = new ArrayList<NameValuePair>(); | |
| } | |
| public void addHeader(NameValuePair header) | |
| { | |
| headers.add(header); | |
| } | |
| public void addPostParam(NameValuePair param) { | |
| postParams.add(param); | |
| } | |
| public JSONObject getData() { | |
| JSONObject jsonObj = new JSONObject(); | |
| for(NameValuePair p : postParams) { | |
| try { | |
| jsonObj.put(p.getName(), p.getValue()); | |
| } catch (JSONException e) { | |
| Log.e(TAG, "JSONException: " + e); | |
| } | |
| } | |
| return jsonObj; | |
| } | |
| @Override | |
| protected void onPreExecute() { | |
| super.onPreExecute(); | |
| if(progressBar != null){ | |
| progressBar.setVisibility(View.VISIBLE); | |
| progressBar.bringToFront(); | |
| } | |
| } | |
| @Override | |
| protected void onPostExecute(Object res){ | |
| if(progressBar != null) | |
| progressBar.setVisibility(View.GONE); | |
| if(res instanceof JSONObject){ | |
| JSONObject response = (JSONObject) res; | |
| Integer status = 400; | |
| String data = null; | |
| try { | |
| status = response.getInt("status"); | |
| } catch (JSONException e) { | |
| e.printStackTrace(); | |
| status = 400; | |
| } catch (NullPointerException e) { | |
| e.printStackTrace(); | |
| status = 400; | |
| } | |
| if(responseListener != null) | |
| responseListener.onResponse(data,status); | |
| }else{ | |
| Exception response = (Exception) res; | |
| responseListener.onError(response); | |
| } | |
| } | |
| public Object request() { | |
| try { | |
| DefaultHttpClient httpClient = new DefaultHttpClient(); | |
| HttpPut put = new HttpPut(this.getUrl()); //-X PUT | |
| for(NameValuePair header : headers) | |
| put.addHeader(header.getName(), header.getValue()); | |
| put.setEntity(new FileEntity(new File(getFilePath()), "image/jpeg")); //@ - absolute path | |
| HttpResponse res = httpClient.execute(put); | |
| JSONObject response = new JSONObject(); | |
| response.put("status", res.getStatusLine().getStatusCode()); | |
| return response; | |
| } catch (ConnectException e){ | |
| e.printStackTrace(); | |
| return e; | |
| } catch (ClientProtocolException e) { | |
| e.printStackTrace(); | |
| return e; | |
| } catch (SocketTimeoutException e){ | |
| e.printStackTrace(); | |
| return e; | |
| } catch (IOException e){ | |
| e.printStackTrace(); | |
| return e; | |
| } catch (JSONException e) { | |
| e.printStackTrace(); | |
| return e; | |
| } | |
| }; | |
| public LinearLayout getProgressBar() { | |
| return progressBar; | |
| } | |
| public void setProgressBar(LinearLayout progressBar) { | |
| this.progressBar = progressBar; | |
| } | |
| protected Object doInBackground(Object... params) { | |
| return request(); | |
| } | |
| public String getUrl() { | |
| return url; | |
| } | |
| public void setUrl(String url) { | |
| this.url = url; | |
| } | |
| public String getMethod() { | |
| return method; | |
| } | |
| public HttpResponseListener getResponseListener() { | |
| return responseListener; | |
| } | |
| public void setResponseListener(HttpResponseListener responseListener) { | |
| this.responseListener = responseListener; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.devniel.braph.listeners; | |
| public interface HttpResponseListener { | |
| public void onResponse(String result, Integer status); | |
| public void onError(Exception error); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.devniel.braph.fragments; | |
| import android.app.Activity; | |
| import android.app.Fragment; | |
| import android.content.Intent; | |
| import android.graphics.Bitmap; | |
| import android.graphics.BitmapFactory; | |
| import android.net.Uri; | |
| import android.os.Bundle; | |
| import android.os.Environment; | |
| import android.provider.MediaStore; | |
| import android.util.Log; | |
| import android.view.LayoutInflater; | |
| import android.view.View; | |
| import android.view.ViewGroup; | |
| import android.widget.Button; | |
| import android.widget.ImageView; | |
| import com.devniel.braph.R; | |
| import com.devniel.braph.listeners.HttpResponseListener; | |
| import com.devniel.braph.utils.HttpFileUploader; | |
| import org.apache.http.message.BasicNameValuePair; | |
| import java.io.ByteArrayOutputStream; | |
| import java.io.File; | |
| import java.io.FileOutputStream; | |
| import java.io.IOException; | |
| import java.text.SimpleDateFormat; | |
| import java.util.Date; | |
| public class PhotoFragment extends Fragment implements View.OnClickListener { | |
| private static final String TAG = "PhotoFragment"; | |
| private static final String ARG_PARAM1 = "param1"; | |
| private static final String ARG_PARAM2 = "param2"; | |
| private String mParam1; | |
| private String mParam2; | |
| private OnFragmentInteractionListener mListener; | |
| private ImageView photo; | |
| public static PhotoFragment newInstance(String param1, String param2) { | |
| PhotoFragment fragment = new PhotoFragment(); | |
| Bundle args = new Bundle(); | |
| args.putString(ARG_PARAM1, param1); | |
| args.putString(ARG_PARAM2, param2); | |
| fragment.setArguments(args); | |
| return fragment; | |
| } | |
| public PhotoFragment() {} | |
| @Override | |
| public void onCreate(Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| if (getArguments() != null) { | |
| mParam1 = getArguments().getString(ARG_PARAM1); | |
| mParam2 = getArguments().getString(ARG_PARAM2); | |
| } | |
| } | |
| @Override | |
| public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { | |
| View view = inflater.inflate(R.layout.fragment_photo, container, false); | |
| Button btn_take_photo = (Button) view.findViewById(R.id.btn_take_photo); | |
| btn_take_photo.setOnClickListener(this); | |
| Button btn_upload_photo = (Button) view.findViewById(R.id.btn_upload_photo); | |
| btn_upload_photo.setOnClickListener(this); | |
| photo = (ImageView) view.findViewById(R.id.photo); | |
| return view; | |
| } | |
| @Override | |
| public void onAttach(Activity activity) { | |
| super.onAttach(activity); | |
| try { | |
| mListener = (OnFragmentInteractionListener) activity; | |
| } catch (ClassCastException e) { | |
| throw new ClassCastException(activity.toString() | |
| + " must implement OnFragmentInteractionListener"); | |
| } | |
| } | |
| @Override | |
| public void onDetach() { | |
| super.onDetach(); | |
| mListener = null; | |
| } | |
| @Override | |
| public void onClick(View view) { | |
| switch (view.getId()) { | |
| case R.id.btn_take_photo: | |
| takePhoto(); | |
| break; | |
| case R.id.btn_upload_photo: | |
| uploadPhoto(); | |
| break; | |
| default: | |
| break; | |
| } | |
| } | |
| /** | |
| * Interface | |
| */ | |
| public interface OnFragmentInteractionListener { | |
| public void onPhoto(Uri uri); | |
| } | |
| /** | |
| * Button On Click Listener | |
| */ | |
| static final int REQUEST_IMAGE_CAPTURE = 1; | |
| static final int REQUEST_TAKE_PHOTO = 1; | |
| public void takePhoto(){ | |
| Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); | |
| // Ensure that there's a camera activity to handle the intent | |
| if (takePictureIntent.resolveActivity(this.getActivity().getPackageManager()) != null) { | |
| // Create the File where the photo should go | |
| File photoFile = null; | |
| try { | |
| photoFile = createImageFile(); | |
| } catch (IOException ex) { | |
| // Error occurred while creating the File | |
| Log.e(TAG, ex.getMessage()); | |
| } | |
| // Continue only if the File was successfully created | |
| if (photoFile != null) { | |
| takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); | |
| startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); | |
| } | |
| } | |
| } | |
| @Override | |
| public void onActivityResult(int requestCode, int resultCode, Intent data) { | |
| if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) { | |
| getPhoto(); | |
| } | |
| super.onActivityResult(requestCode, resultCode, data); | |
| } | |
| String mCurrentPhotoPath; | |
| private File createImageFile() throws IOException { | |
| // Create an image file name | |
| String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); | |
| String imageFileName = "JPEG_" + timeStamp + "_"; | |
| File storageDir = Environment.getExternalStoragePublicDirectory( | |
| Environment.DIRECTORY_PICTURES); | |
| File image = File.createTempFile( | |
| imageFileName, /* prefix */ | |
| ".jpg", /* suffix */ | |
| storageDir /* directory */ | |
| ); | |
| // Save a file: path for use with ACTION_VIEW intents | |
| mCurrentPhotoPath = image.getAbsolutePath(); | |
| return image; | |
| } | |
| private void getPhoto() { | |
| Log.d(TAG, "PHOTO : " + photo.toString()); | |
| // Get the dimensions of the View | |
| int targetW = photo.getWidth(); | |
| int targetH = photo.getHeight(); | |
| // Get the dimensions of the bitmap | |
| BitmapFactory.Options bmOptions = new BitmapFactory.Options(); | |
| bmOptions.inJustDecodeBounds = true; | |
| BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); | |
| Log.d(TAG, "Current photo path : " + mCurrentPhotoPath); | |
| int photoW = bmOptions.outWidth; | |
| int photoH = bmOptions.outHeight; | |
| // Determine how much to scale down the image | |
| int scaleFactor = 1; | |
| if(targetW > 0 && targetH > 0) | |
| scaleFactor = Math.min(photoW/targetW, photoH/targetH); | |
| // Decode the image file into a Bitmap sized to fill the View | |
| bmOptions.inJustDecodeBounds = false; | |
| bmOptions.inSampleSize = scaleFactor; | |
| bmOptions.inPurgeable = true; | |
| Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); | |
| photo.setImageBitmap(bitmap); | |
| File f = new File(Environment.getExternalStorageDirectory() | |
| + File.separator + "devniel.jpg"); | |
| ByteArrayOutputStream bytes = new ByteArrayOutputStream(); | |
| bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes); | |
| try { | |
| f.createNewFile(); | |
| FileOutputStream fo = new FileOutputStream(f); | |
| fo.write(bytes.toByteArray()); | |
| fo.close(); | |
| mCurrentPhotoPath = f.getAbsolutePath(); | |
| } catch (IOException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| private void uploadPhoto() { | |
| HttpFileUploader request = new HttpFileUploader(); | |
| request.setUrl("https://dal05.objectstorage.softlayer.net/v1/AUTH_2809ef13-5269-47b8-a204-8e6adeaf53f6/PDTP/photos/devniel.jpg"); | |
| request.addHeader(new BasicNameValuePair("X-Auth-Token", "AUTH_tkbf368f3b5b56433b913a7d6dcda32dee")); | |
| request.setFilePath(mCurrentPhotoPath); | |
| request.setFileType("image/jpeg"); | |
| request.setResponseListener(new HttpResponseListener() { | |
| @Override | |
| public void onResponse(String result, Integer status) { | |
| Log.d(TAG, "RESPONSE : " + status); | |
| } | |
| @Override | |
| public void onError(Exception error) { | |
| } | |
| }); | |
| request.execute(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment