0

I am capturing image from camera and send it to server.After successfully posting to server ,i am displaying the image as background in the Relative layout.My problem is that the quality of image got lost and image is stretched when displayed in the background of relative layout. Screen Shot is given below:

Screenshot 1

Screenshot 2

On clicking Camera

//On clicking Camera


 imgCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Checking camera availability
            if (!isDeviceSupportCamera()) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! Your device doesn't support camera",
                        Toast.LENGTH_LONG).show();
                // will close the app if the device doesn't have camera
                finish();
            } else {
                //cameraClick(view);
                captureImage();
            }
        }
    });

CaptureImage() Method:

private void captureImage() {
    Log.e("Capture Image", "Called");
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // creating Dir to save clicked Photo
    String root = Environment.getExternalStorageDirectory().toString();
    Log.e("root", root);
    String directory_path = root + "/cam_intent/";
    File myDir = new File(directory_path);
    myDir.mkdirs();
    // save clicked pic to given dir with given name
    File file = new File(myDir, "MyPhoto.jpg");
    fileUri = Uri.fromFile(file);
    Log.e("Uri of File", String.valueOf(fileUri));
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

onActivityResult()

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.e("onActivityResult", "Called");
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
        launchUploadActivity(true);
    }
}

launchUploadActivity()

 private void launchUploadActivity(boolean isImage) {
    if (fileUri.getPath() != null) {
        // Displaying the image or video on the screen

        Log.e("Launch Upload Activity", "Called");
        previewMedia(isImage);
    } else {
        Toast.makeText(getApplicationContext(),
                "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
    }
}

previewMedia()

 private void previewMedia(boolean isImage) {
    // Checking whether captured media is image or video
    if (isImage) {
        Log.e("Preview Media", "Called");          

        //Uploading image to server
        new UploadFileToServer().execute();         
    }

UploadFileToServer

    private class UploadFileToServer extends AsyncTask<Void, Integer, String> {

    @Override
    protected void onPreExecute() {
        // setting progress bar to zero
        // progressBar.setProgress(0);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // Making progress bar visible
        //progressBar.setVisibility(View.VISIBLE);
        //Making progress dialog visible
        progressDialog.show();

        // updating progress bar value
        // progressBar.setProgress(progress[0]);

        // updating percentage value
        //txtPercentage.setText(String.valueOf(progress[0]) + "%");
    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        Log.e("upload File", "called");
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(file_upload_url);

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new AndroidMultiPartEntity.ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });


            // Adding file data to http body
            if (val == 0) {

                Log.e("val = ", String.valueOf(val));
                File sourceFile = new File(fileUri.getPath());
                if (sourceFile != null) {
                    Log.e("SoureFile", String.valueOf(sourceFile));
                    photosize = 0;
                    entity.addPart("image", new FileBody(sourceFile));
                } else {
                    photosize = 1;
                    Toast.makeText(ProfileActivity.this, "Please Upload Your Image", Toast.LENGTH_LONG).show();
                }


            } else {

                File sourceFile = new File(picturePath);
                if (sourceFile != null) {
                    photosize = 0;
                    entity.addPart("image", new FileBody(sourceFile));
                } else {
                    photosize = 1;
                    Toast.makeText(ProfileActivity.this, "Please Upload Your Image", Toast.LENGTH_LONG).show();
                }

            }

            totalSize = entity.getContentLength();
            Log.e("Total Size", String.valueOf(totalSize));
            httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;

    }

    @Override
    protected void onPostExecute(String result) {
        Log.e("UpLoad Server", "Response from server: " + result);
        try {
            JSONObject jsonObject = new JSONObject(result);
            String statusCode = jsonObject.getString("statusCode");
            if (statusCode.equals("200")) {
                JSONObject detail = jsonObject.getJSONObject("detail");
                String relativePath = detail.getString("relative_path");
                JSONObject uploadData = detail.getJSONObject("upload_data");
                String fileName = uploadData.getString("file_name");
                //Getting Base URL
                base_url = apiConfiguration.getApi();
                completeURL = base_url + relativePath + "/" + fileName;
                Log.e("Complete URl", completeURL);
                //Entering the new value of complete url in shared preference
                //editor.remove(Prefs_Registration.get_user_complete_url);
                editor.putString(Prefs_Registration.get_user_complete_url, completeURL);
                editor.commit();
                new GetBitmapFromURL().execute();
            } else
                Toast.makeText(getApplicationContext(), "Image not uploaded", Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        progressDialog.dismiss();

        // showing the server response in an alert dialog
        //showAlert(result);

        super.onPostExecute(result);
    }

    /**
     * Method to show alert dialog
     */
    private void showAlert(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
        builder.setMessage(message)
                .setTitle("Response from Servers")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // do nothing
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

}

GetImageFromURL

 // Get Image from Thumbnail URL
class GetBitmapFromURL extends AsyncTask<String, String, Bitmap> {
    Bitmap myBitmap;

    @Override
    protected Bitmap doInBackground(String... strings) {
        URL url = null;
        try {
            url = new URL(completeURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            myBitmap = BitmapFactory.decodeStream(input);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return myBitmap;

    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {

        Drawable dr = new BitmapDrawable(bitmap);
        Log.e("DrawableN", String.valueOf(dr));
        //Setting the image
        relativeLayout.setBackgroundDrawable(dr);
    }
}

Inside onPostExecute() method i am setting the image in the background of relative layout .

XML

<RelativeLayout
    android:id="@+id/rel"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:layout_marginBottom="@dimen/margin10"
    android:layout_marginLeft="@dimen/margin10"
    android:layout_marginRight="@dimen/margin10"
    android:layout_marginTop="@dimen/margin10">

    <ImageView
        android:id="@+id/arrowProfile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="@dimen/padding10"
        android:src="@drawable/back_signup" />

    <com.almabay.almachat.circularImageView.CircularImageView
        android:id="@+id/cam"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:paddingRight="@dimen/padding10"
        android:background="@drawable/camera1"/>

    <TextView
        android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/status"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="@dimen/margin20"
        android:paddingLeft="@dimen/padding10"
        android:text="User Name"
        android:textColor="#ffffff"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:paddingLeft="@dimen/padding10"
        android:text="Status of user"
        android:textColor="#ffffff" />
</RelativeLayout>

I am sending the image as multipart to server.Please tell me how can i maintain the quality of the image while rendering on Relative layout.

Deepak Rattan
  • 1,279
  • 7
  • 21
  • 47
  • You posted or better said dumped much to much code. Should we dig through that all? Just post the code where it is all about. Just a little bit of code that causes the problem. – greenapps Feb 18 '16 at 14:28
  • Please check the code now.I have only mentioned the code where i am sending the image to server and displaying it in the relative layout. – Deepak Rattan Feb 19 '16 at 03:58
  • Loss of quality and stretching are two things. Are both really happening? We can see the stretching yes. – greenapps Feb 20 '16 at 10:08
  • I think only stretching is there. – Deepak Rattan Feb 20 '16 at 10:09
  • I do not understand what this has to do with posting to a server. Cant you just post the code that puts an image file in an image view? Otherwise explain why they are are connected first. – greenapps Feb 20 '16 at 10:11
  • You can set a flag for the image view not to stretch the bitmap i think. – greenapps Feb 20 '16 at 10:12
  • I have already added my code that is sending image to the server.Actually the problem is that i am setting the image in the background of a relative layout whose width is match_parent and height is 150dp. I am not displaying the image in the image view. – Deepak Rattan Feb 20 '16 at 10:20
  • `I have already added my code that is sending image to the server.`. Sorry. I asked you to remove it as it has nothing to do with your problem i would think. You should post only relevant code. – greenapps Feb 20 '16 at 10:32
  • Please check my edited code now.I have added the part of code that is setting the image in the background of relative layout . – Deepak Rattan Feb 20 '16 at 10:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/104021/discussion-between-deepakr-and-greenapps). – Deepak Rattan Feb 20 '16 at 10:39
  • Yes. But what about `I am capturing image from camera and send it to server.`. ???? You are not sending to a server. You are downloading an image from a server. – greenapps Feb 20 '16 at 10:40
  • Yes that is correct.I am capturing the image from the camera and then sending it to server in multipart.When my POST is successful i am using AsyncTask to get the bitmap from the URL of the image and set it in the background of relative layout.Here i have specified only the code that is actually setting the image in the background . – Deepak Rattan Feb 20 '16 at 10:44
  • That is not the way to clear a problem as you and we certainly do not know where things go wrong now. You should post here a reproducable problem. Beginning with an image file on your phone which you set to your relative layout. Post code that we can try too is the idea. – greenapps Feb 20 '16 at 10:47
  • You also did not tell why you first would upload an image to your server and then download it again to display it? Why so? And is it the same image? Or did the server change it? We cannot see and know. – greenapps Feb 20 '16 at 10:49
  • Strange: you post an image to your server and then get a bitmap from an url. We would rather see that you said that you were downloading the same image from an url. – greenapps Feb 20 '16 at 10:50
  • I have added the complete code now.Please check.On clicking camera firstly i am Posting image to server.If the post is successful then only i am setting the same image in the background of Relative layout . – Deepak Rattan Feb 20 '16 at 11:00
  • This is silly. We dont want to see all that code. You were asked to put only code here that reproduces your problem. Sorry i will not even look at your code anymore. You know what you have to do instread. – greenapps Feb 20 '16 at 11:50
  • it is ok if you do not want to help me.You were demanding the whole code.This is complete complete code from capturing the image from the camera to uploading it to server. I know my issue.Image is stretched just because it is displayed in the relative layout of a fixed height.That is why it is stretched,I have already specified it. – Deepak Rattan Feb 20 '16 at 11:54

1 Answers1

0

The aspect ratio of your ImageView should be equal to the aspect ratio of the captured image.

Endre Börcsök
  • 477
  • 1
  • 8
  • 19