nurzain-pradana

Untitled

Jun 7th, 2020
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. public class UploadImage {
  2. ApiInterface Service;
  3. retrofit2.Call<ResultMember> Call;
  4.  
  5. String encodedString;
  6. String fileName;
  7. String imgPath;
  8.  
  9. public UploadImage(String imgPath, String fileName) {
  10. this.imgPath = imgPath;
  11. this.fileName = fileName;
  12. }
  13.  
  14. //when upload button is clicked
  15. public void uploadImage() {
  16. //when image is selected from gallery
  17. if (imgPath != null && !imgPath.isEmpty()) {
  18. //convert image to string using base64
  19. encodeImagetoString(imgPath);
  20. //when image is not selected from gallery
  21. } else {
  22. Log.e("Error", "You must select image from gallery before you try to upload");
  23. }
  24. }
  25.  
  26. //AsyncTask - To conver Image to String
  27. @SuppressLint("StaticFieldLeak")
  28. public void encodeImagetoString(String imgPath) {
  29. new AsyncTask<Void, Void, String>() {
  30. protected void onPreExecute() {
  31. }
  32.  
  33. @Override
  34. protected String doInBackground(Void... params) {
  35. BitmapFactory.Options options;
  36. options = new BitmapFactory.Options();
  37. options.inSampleSize = 3;
  38. Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
  39. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  40. // Must compress the image to reduce image size to make upload easey
  41. bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
  42. byte[] byte_arr = stream.toByteArray();
  43.  
  44. //encode image to string
  45. encodedString = Base64.encodeToString(byte_arr, 0);
  46. return "";
  47. }
  48.  
  49. @Override
  50. protected void onPostExecute(String s) {
  51. //trigger image upload
  52. makeHTTPCall();
  53. }
  54. }.execute(null, null, null);
  55. }
  56.  
  57. //make http call to upload image to php server
  58. public void makeHTTPCall() {
  59. Service = Api.getApi().create(ApiInterface.class);
  60. uploadImage();
  61. Call = Service.uploadPhoto(encodedString, fileName);
  62. Call.enqueue(new Callback<ResultMember>() {
  63. @Override
  64. public void onResponse(retrofit2.Call<ResultMember> call, Response<ResultMember> response) {
  65. Log.d("UPLOAD", response.toString());
  66. }
  67.  
  68. @Override
  69. public void onFailure(retrofit2.Call<ResultMember> call, Throwable t) {
  70. Log.d("UPLOAD GAGAL", t.toString());
  71. }
  72. });
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment