图像使用意图上传

时间:2015-09-28 14:00:35

标签: android eclipse android-intent image-uploading image-gallery

我试图为我的Android移动应用程序上传图片。代码适用于从Gallery文件夹上传的图像。但是,如果我从"最近图像","文档","下载"中选择任何图像。图像路径未提取,无法上传图像。能否帮助我解决这个问题呢。

这是我的编码供您参考:

package com.example.imageupload;



public class MainActivity extends Activity {

    private ImageView image;
    private Button uploadButton;
    private Bitmap bitmap;
    private Button selectImageButton, takeImageButton;
    String link = uri;
    // number of images to select
    private static final int PICK_IMAGE = 1;
    private static final int CAMERA_REQUEST = 1888;

    /**
     * called when the activity is first created
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // find the views
        image = (ImageView) findViewById(R.id.uploadImage);
        uploadButton = (Button) findViewById(R.id.uploadButton);
        takeImageButton = (Button) findViewById(R.id.takeImageButton);
        selectImageButton = (Button) findViewById(R.id.selectImageButton);

        selectImageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                selectImageFromGallery();

            }
        });


        // when uploadButton is clicked
        uploadButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // new ImageUploadTask().execute();
                Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT)
                        .show();
                uploadTask();
            }
        });
    }

    protected void uploadTask() {
        // TODO Auto-generated method stub
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, 100, bos);
        byte[] data = bos.toByteArray();
        String file = Base64.encodeToString(data, 0);
        Log.i("base64 string", "base64 string: " + file);
        new ImageUploadTask(file).execute();
    }

    /**
     * Opens dialog picker, so the user can select image from the gallery. The
     * result is returned in the method <code>onActivityResult()</code>
     */
    public void selectImageFromGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                PICK_IMAGE);
    }

    /**
     * Retrives the result returned from selecting image, by invoking the method
     * <code>selectImageFromGallery()</code>
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
                && null != data) {

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            /*
             * Cursor cursor = getContentResolver().query(selectedImage,
             * filePathColumn, null, null, null);
             */

            Cursor cursor = managedQuery(selectedImage, filePathColumn, null,
                    null, null);
            cursor.moveToFirst();

            // int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            int columnIndex = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String picturePath = cursor.getString(columnIndex);
            Log.i("picturePath", "picturePath: " + picturePath);
            cursor.close();

            decodeFile(picturePath);

        }   }


    public void decodeFile(String filePath) {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 1024;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);

        image.setImageBitmap(bitmap);
    }

    /**
     * The class connects with server and uploads the photo
     * 
     * 
     */
    class ImageUploadTask extends AsyncTask<Void, Void, String> {

        String base64_string;

        public ImageUploadTask(String file) {
            // TODO Auto-generated constructor stub
            this.base64_string = file;
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub

            ArrayList<NameValuePair> postData;
            postData = new ArrayList<NameValuePair>();

            JSONObject parentData = new JSONObject();
            JSONObject childData = new JSONObject();

            try {

                childData.put("fileContent", base64_string);
                childData.put("fileName", "droid.jpeg");
                childData.put("fileType", "I");

                // System.out.println(childData);

                parentData.put("mobile", childData);

                System.out.println(parentData);

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

            // postData.add(new BasicNameValuePair("User",
            // childData.toString()));

            InputStream is = null;
            String jsonResponse = "";
            JSONObject jObj = null;

            try {

                DefaultHttpClient httpClient = new DefaultHttpClient();

                HttpPost request = new HttpPost(
                        "URL");

                request.setHeader("Content-Type", "application/json");
                request.setEntity(new StringEntity(parentData.toString()));

                HttpResponse httpResponse = httpClient.execute(request);
                System.out.println(httpResponse);

                // HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                System.out.println(httpEntity);
                is = httpEntity.getContent();
                System.out.println(is);
                System.out.println(is.toString());

                try {
                    Log.e("@@@@@@@@@@", "@@@@@@@@@@@");
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    jsonResponse = sb.toString();
                    Log.e("JSON", "Check Json: " + jsonResponse);

                } catch (Exception e) {
                    Log.e("Buffer Error",
                            "Error converting result " + e.toString());
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

    }
}

1 个答案:

答案 0 :(得分:1)

我刚刚更改了以下代码:

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

    if (requestCode == PICK_IMAGE && null != data) {
        if (resultCode == getActivity().RESULT_OK) {
            selectedImage = data.getData();
            Log.i("selectedImage", "selectedImage: " + selectedImage.toString());
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();

            Log.i("columnIndex", "columnIndex: " + columnIndex);

            String picturePath = cursor.getString(columnIndex);
            Log.i("picturePath", "picturePath: " + picturePath);
            cursor.close();

        }
    }


}

  public void selectImageFromGallery(){
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, PICK_IMAGE);}