通过相机捕获的图像质量丢失

时间:2016-02-18 12:57:26

标签: android android-camera

我从摄像头捕获图像并将其发送到服务器。成功发布到服务器后,我在相对布局中将图像显示为背景。我的问题是图像质量丢失,图像在显示时被拉伸相对布局的背景。屏幕截图如下:

Screenshot 1

Screenshot 2

点击相机

0xFF

CaptureImage()方法

//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();
            }
        }
    });

onActivityResult()

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);
}

launchUploadActivity()

 @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);
    }
}

previewMedia()

 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();
    }
}

UploadFileToServer

 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();         
    }

GetImageFromURL

    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();
    }

}

在onPostExecute()方法中,我在相对布局的背景中设置图像。

XML

 // 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);
    }
}

我将图像作为multipart发送到服务器。请告诉我如何在相对布局上渲染时保持图像的质量。

1 个答案:

答案 0 :(得分:0)

ImageView的宽高比应该等于捕获图像的宽高比。