简体   繁体   English

如何在Android中将图像上传到服务器

[英]How to upload image to the server in android

i want to upload Image in Same Size choosed From Gallary.i.Uploaded to the server ..But Image is uploaded On Server like Compressed....like This Image Below 我想上传从Gallary.i中选择的相同大小的图像。上载到服务器..但是图像像压缩的一样在服务器上上传....像下面的图像 在此处输入图片说明

i want to upload Image in Same Size ...or how to set Cropped Intent In This Methode 我想上传相同大小的图像...或如何在此方法中设置裁剪的意图

here Is My Code To Adjust Image 这是我的代码来调整图像

public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
        case 123987:
            if (resultCode == RESULT_OK) {
                try {

                    Uri selectedImageUri = data.getData();
                    selectedImagePath = getPath(selectedImageUri);
                    Log.d("selectedImagePath", "selectedImagePath = " + selectedImagePath);

                    ParseImage _ParseImage = new ParseImage();
                    _ParseImage.activityContext = this;
                    _ParseImage.execute(selectedImagePath);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            }

            break;

        case 1234:
            if (resultCode == RESULT_OK) {
                try {

                    final_bitmap = null;

                    String realPath = Environment.getExternalStorageDirectory() + "/" + fileName;

                    selectedImagePath = realPath;

                    new BitmapFactory();

                    Bitmap btmp = setBitmap(selectedImagePath);

                    /*String path = selectedImagePath.toLowerCase();
                    if (path.contains("dcim") && path.contains("camera")) {
                        btmp = RotateBitmap(btmp, 90);
                    }*/

                    int o_width = btmp.getWidth();
                    int o_height = btmp.getHeight();

                    // w=1840, h=3264
                    float large_image_ratio = 300.00f;

                    //Log.d("orignal_image", "orignal_image = " + o_width + " , " + o_height);
                    if (o_width > o_height) {

                        if (o_width >= large_image_ratio) {

                            float temp_w = (float)o_width/(float)large_image_ratio;
                            //int temp_h = o_height/large_image_ratio;

                            //Log.d("temp_w", "temp_w = " + temp_w);

                            int scales_width = (int) large_image_ratio;
                            int scales_height = (int) Math.round(o_height/temp_w);

                            //Log.d("scale_image-if", "scale_image-if = " + scales_width + " , " + scales_height);

                            final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);

                        } else {
                            final_bitmap = btmp;
                        }
                    } else {


                        if (o_height >= large_image_ratio) {

                            //int temp_w = o_width/large_image_ratio;
                            float temp_h = (float)o_height/(float)large_image_ratio;

                            //Log.d("temp_h", "temp_h = " + temp_h);

                            int scales_width = (int) Math.round(o_width/temp_h);
                            int scales_height = (int) large_image_ratio;

                            //Log.d("scale_image-else", "scale_image-else = " + scales_width + " , " + scales_height);

                            final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
                        } else {
                            final_bitmap = btmp;
                        }

                    }

                    img.setImageBitmap(final_bitmap);

                    Image_into_Byte(final_bitmap);
                    img.setVisibility(View.VISIBLE);
                    btn_upload.setEnabled(true);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            break;
        }
    }

    public class ParseImage extends AsyncTask<String, Void, String> {

        private ProgressDialog dialog;
        protected Context activityContext;


        @Override
        protected void onPreExecute() {
            try {
                final_bitmap = null;

                this.dialog = new ProgressDialog(activityContext, AlertDialog.THEME_HOLO_LIGHT);
                //this.dialog.setTitle(title);
                this.dialog.setMessage("Loading Image");
                this.dialog.setCanceledOnTouchOutside(false);
                this.dialog.show();


            } catch (Exception e) {
                // TODO: handle exception
            }
        }

        protected String doInBackground(String... image_path) {
            try {

                new BitmapFactory();

                Bitmap btmp = setBitmap(selectedImagePath);

                /*String path = selectedImagePath.toLowerCase();
                if (path.contains("dcim") && path.contains("camera")) {
                    btmp = RotateBitmap(btmp, 90);
                }*/

                int o_width = btmp.getWidth();
                int o_height = btmp.getHeight();

                // w=1840, h=3264
                float large_image_ratio = 300.00f;

                //Log.d("orignal_image", "orignal_image = " + o_width + " , " + o_height);
                if (o_width > o_height) {

                    if (o_width >= large_image_ratio) {

                        float temp_w = (float)o_width/(float)large_image_ratio;
                        //int temp_h = o_height/large_image_ratio;

                        //Log.d("temp_w", "temp_w = " + temp_w);

                        int scales_width = (int) large_image_ratio;
                        int scales_height = (int) Math.round(o_height/temp_w);

                        //Log.d("scale_image-if", "scale_image-if = " + scales_width + " , " + scales_height);

                        final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);

                    } else {
                        final_bitmap = btmp;
                    }
                } else {


                    if (o_height >= large_image_ratio) {

                        //float temp_w = o_width/large_image_ratio;
                        float temp_h = (float)o_height/(float)large_image_ratio;

                        //Log.d("temp_h", "temp_h = " + temp_h);

                        int scales_width = (int) Math.round(o_width/temp_h);
                        int scales_height = (int) Math.round(o_width/temp_h);

                        //Log.d("scale_image-else", "scale_image-else = " + scales_width + " , " + scales_height);

                        final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
                    } else {
                        final_bitmap = btmp;
                    }

                }

            } catch (Exception e) {
                // TODO: handle exception
            }
            return "complete";
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                this.dialog.cancel();
                SaveBitmap(final_bitmap);

                // final_bitmap
                img.setImageBitmap(final_bitmap);

                Image_into_Byte(final_bitmap);

                btn_upload.setEnabled(true);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
// crop intent function

    public void cropCapturedImage(Uri picUri){
      //call the standard crop action intent 
      Intent cropIntent = new Intent("com.android.camera.action.CROP");
      //indicate image type and Uri of image
      cropIntent.setDataAndType(picUri, "image/*");
      //set crop properties
      cropIntent.putExtra("crop", "true");
      //indicate aspect of desired crop
      cropIntent.putExtra("aspectX", 1);
      cropIntent.putExtra("aspectY", 1);
      //indicate output X and Y
      cropIntent.putExtra("outputX", 256);
      cropIntent.putExtra("outputY", 256);
      //retrieve data on return
      cropIntent.putExtra("return-data", true);
      //start the activity - we handle returning in onActivityResult
      startActivityForResult(cropIntent, 2);
     }


get uri from gallery selected image

    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else { 
            cursor.moveToFirst(); 
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }


    use this function when get image  from gallery and camera :-

    // camera  on activityresult
    cropCapturedImage(Uri.fromFile(file));


    // gallery 

    cropCapturedImage(Uri.fromFile(getRealPathFromURI(data.getData())));

You should make Base64 encoded string of Bitmap and send this image string to server via NameValuePair with url . 你应该做Base64编码的字符串, Bitmap ,并通过该图像串发送到服务器NameValuePairurl Use AsyncTask<...> for uploading image like for example: 使用AsyncTask<...>上载图像,例如:

private class ImgUploadingTask extends AsyncTask<String, Void, String>
{

    //do your stuff onPreExecute()       

   @Override
        protected String doInBackground(String... params) 
        {
           try
           {

            String imageDataString = null;

            HttpClient client = new DefaultHttpClient();

            HttpPost post = new  HttpPost(server_url);

            List<NameValuePair> list = new ArrayList<NameValuePair>();

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            bitmap.compress(CompressFormat.JPEG, 100, bos);

            byte[] data = bos.toByteArray();

            imageDataString = Base64.encodeToString(data, Base64.DEFAULT);

            list.add(new BasicNameValuePair("image", imageDataString));

            post.setEntity(new UrlEncodedFormEntity(list));

            HttpResponse resp = client.execute(post);

            HttpEntity entity = resp.getEntity();

            String response = EntityUtils.toString(entity);

            Log.d("Response ", response);
          }
          catch(Exception e){
             e.printStackTrace();
          }
          return null;

        }
}

    //do your stuff onPostExecute()

After this you have to set your server side code, accept this Base64 encoded String and decode it on server side to get real image. 之后,您必须设置服务器端代码,接受此Base64 encoded String并在服务器端decode以获得真实图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM