-1

Task

"Send an image by using an HTTP POST request on the endpoint /images with either a multipart-form-encoded, or base64 encoded data parameter."

I am using Cloudsight API for my image recognition project. Refference http://docs.cloudsight.apiary.io/#reference/0/images-collection/send-an-image-for-identification

Problem

I need to send an image from gallery encoded into base64format, but I get server error 500. I can't seem to find the problem in my code maybe the image is not encoded properly?

Code

    private String uploadData(String url) {
        String sResponse = "";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url+"/images");
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("Authorization", "CloudSight API_KEY");

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();

                String encImage = Base64.encodeToString(data, Base64.DEFAULT);

            JSONObject obj = new JSONObject();

            obj.put("remote_image_url",encImage );
            obj.put("locale", "en");
            httpPost.setEntity(new StringEntity(obj.toString()));

            HttpResponse response = httpClient.execute(httpPost, localContext);
            int responseCode = response.getStatusLine().getStatusCode();
            sResponse = inputStreamToString(
                    response.getEntity().getContent()).toString();
            Log.i("ResponseString", sResponse);
            Log.i("code", responseCode+"");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return sResponse;
    }

    private class uploadImage1 extends AsyncTask<String, String, String>{
        ProgressBar progressBar = new ProgressBar(getApplication(), null, android.R.attr.progressBarStyleSmall);

        protected void onPreExecute() {
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            progressBar.setVisibility(View.VISIBLE);
           super.onPreExecute();


        }

        @Override
        protected String doInBackground(String... params) {
            String url = params[0];
            String sResponse = uploadData(url);
            return sResponse;

        }
    }

Edit

"Note: we recommend an image resolution no higher than 1024x, and a JPEG compression level between 5-8. We resize images internally otherwise, and it could slow down the request process."

So i need to resize my image before i send it? Can you share some example?

CDub
  • 13,146
  • 4
  • 51
  • 68
  • Server 500 is for internal server error. Kindly ask server team for resolution. – Nilesh Deokar Oct 05 '17 at 08:02
  • "Note: we recommend an image resolution no higher than 1024x, and a JPEG compression level between 5-8. We resize images internally otherwise, and it could slow down the request process." So i need to resize my image before i send it? Can you share some example? – Купувај Онлајн Oct 05 '17 at 08:04
  • Welcome to SO. 1) Put more effort into formatting your code 2) Why are you using snippets? 3) Is this an assignment? Next time please format properly so we understand what the source task is and what are the questions you pose 4) Ask a specific question, instead of multiple random and broad ones - noone will share examples of complete solutions with you, this is not what this site is for. 5) Please read through this before posting anymore: https://stackoverflow.com/help/asking – Maciej Jureczko Oct 05 '17 at 08:30
  • Hi and thanks for the suggestion. Sorry for the bad question structure, i updated my refference for the API i am using – Купувај Онлајн Oct 05 '17 at 08:37
  • Hi - `remote_image_url` is for the url of an image on the web. If you are sending the image yourself as base64 encoded then the parameter you want is just `image`. – mccalljt Oct 05 '17 at 22:22
  • Unfortunately I stil get the 500 error from server – Купувај Онлајн Oct 06 '17 at 07:21

1 Answers1

0

Main Activity

              try {
                    Bitmap bitmap = photo();
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    bitmap.recycle();
                    byte[] array = stream.toByteArray();
                    encoded_String = Base64.encodeToString(array, 0);

                } catch (Exception e) {

                }
                new BackgroundWorker().execute(encoded_String);

Background Activity

protected String doInBackground(String... params) {
    String login_url="Your link";
    try {
            String post;
            String number=params[0];
            String name=params[1];
            encoded_String=params[2];
            URL url = new URL(login_url);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("POST");
            http.setDoInput(true);
            http.setDoOutput(true);
            OutputStream out = http.getOutputStream();
            BufferedWriter buffer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            if(encoded_String.equals("null")) {
                post = URLEncoder.encode("number", "UTF-8") + "=" + URLEncoder.encode(number, "UTF-8") + "&" +
                        URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
            }else{
                post = URLEncoder.encode("number", "UTF-8") + "=" + URLEncoder.encode(number, "UTF-8") + "&" +
                        URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("encoded_photo", "UTF-8") + "=" + URLEncoder.encode(encoded_String, "UTF-8");
            }
            buffer.write(post);
            buffer.flush();
            buffer.close();
            out.close();

And php file code is

if(isset($_POST["encoded_photo"])){
    $encoded_string = $_POST["encoded_photo"];
    $image_name = rand().time().".jpg";

    $decoded_string = base64_decode($encoded_string);

    $path = 'image/'.$image_name;

    $file = fopen($path, 'wb');

    $is_written = fwrite($file, $decoded_string);
    fclose($file);
    $sql="INSERT INTO names(Number,Name,Refferel,photo) VALUES ('$number','$name','$Refferel','$path')";
    $result=mysqli_query($conn,$sql);
    if($result==true){
        echo "success";
    }
Muhammad Aqeel
  • 81
  • 1
  • 11