在上传到服务器之前调整jpg图像的大小

时间:2017-09-14 10:36:39

标签: android image android-volley image-resizing image-compression

在我的应用程序中,我需要一个图像选择器选项,用户可以从库中选择图像,也可以从相机中取出图像将其上传到服务器。现在,我使用volley库从应用程序发送Post请求。图像应为jpg格式,因为服务器仅支持jpeg格式,而不是10,000字节。在我的代码中我到目前为止所做的,拍摄图像或从图库中选择图像。制作一个调整图像大小的方法,但现在实际上正在运行。然后,一旦用户从图库中选择图像,请尝试上传图像。此时图像被命中服务器,也从服务器中删除图像,但实际上没有显示图像,因为压缩错误。我坚持这个问题,但无法解决问题。如何将jpeg图像调整为10,000字节并将其作为参数发送到volley?

以下是我的照片上传功能代码

private void galleryIntent()
{
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);

}

private void cameraIntent()
{
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_CAMERA);
    }
}

private void uploadImage()
{
    StringRequest stringRequest = new StringRequest( Request.Method.POST, UPLOAD_URL+mail,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                    //Showing toast message of the response
                Toast.makeText(getActivity(), response , Toast.LENGTH_LONG).show();
                Log.d( "Error Response"," "+response );
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                    //Showing toast
                Toast.makeText(getActivity(), volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                Log.d( "Volley Error"," "+volleyError );
            }
        }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

                //Problem in this line as the image is on jpeg format in server side.

              //Creating parameters
                    //Here I want to set resize image as parameter 
            Map<String,String> params = new Hashtable<String, String>();
            String imageData=imageToString( bitmap );
            params.put("image", imageData);

            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String, String> headers = new HashMap<>();
            headers.put( "Content-Type", "image/jpeg" );
            Log.d( "headers", String.valueOf( headers ) );
            return headers;
        }
    };
        //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        //Adding request to the queue
    requestQueue.add(stringRequest);
}


// Here I want to resize the jpeg image into 10 byte.
// I have an idea but do not know actually how can I implement that.
 public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
    int width = 200;
    int height = 200;
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // CREATE A MATRIX FOR THE MANIPULATION
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);

    // "RECREATE" THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(
            bm, 0, 0, width, height, matrix, false);
    bm.recycle();
    return resizedBitmap;
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_FILE){
            Uri filepath=data.getData();
            try {
                InputStream inputStream=getActivity().getContentResolver().openInputStream( filepath );
                bitmap= BitmapFactory.decodeStream( inputStream );
                image.setImageBitmap( bitmap );

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    else if (requestCode == REQUEST_CAMERA) {

        if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG,10, bytes);
            File destination = new File(Environment.getExternalStorageDirectory(),"temp.jpg");
            FileOutputStream fo;
            try {
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.setImageBitmap(thumbnail);
        }
    }

    uploadImage();
}

0 个答案:

没有答案