-1

Still new to android/java dev but getting there, I have created a class that uploads an image to a php server but the image is currently hardcoded, I want to take it a step further now by selecting an image from gallery and then uploading it.

I am not sure how to use onActivityResult() and pass the results to a class? Hope you can help.

The onClick event is on profile.java and the upload script is on ImageUpload.java, so need to get the result from profile to ImageUpload

Also, how would I change the below to the correct code?

       Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);           
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
    byte [] byte_arr = stream.toByteArray();
    String image_str = Base64.encodeBytes(byte_arr);
    final ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

    nameValuePairs.add(new BasicNameValuePair("image",image_str));
    nameValuePairs.add(new BasicNameValuePair("username",IMService.USERNAME));

     Thread t = new Thread(new Runnable() {              
    public void run() {
          try{
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost("http://127.0.0.1/upimage.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 HttpResponse response = httpclient.execute(httppost);
                 final String the_string_response = convertResponseToString(response);
                 runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(UserProfile.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                          
                        }
                    });

             }catch(final Exception e){


                   System.out.println("Error in http connection "+e.toString());
             }  
    }
4

2 回答 2

0
// try this way
final private int PICK_IMAGE_USER_AVATAR = 1;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE_USER_AVATAR);

private String selectedImagePathPhotoUpload;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
       if (requestCode == PICK_IMAGE_UPLOAD_PHOTO) {
            selectedImagePathPhotoUpload = getAbsolutePath(data.getData());
            imgUploadPhoto.setVisibility(View.VISIBLE);
            imgUploadPhoto.setImageBitmap(decodeFile(selectedImagePathPhotoUpload));
        }
     }

}

public String getAbsolutePath(Uri uri) {
    String[] projection = { MediaColumns.DATA };
        @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
    return null;
}

public Bitmap decodeFile(String path) {
    try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 70;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return null;

}
于 2013-11-08T07:30:53.067 回答
0

请参阅此示例代码 ImageGalleryDemoActivity 有一个按钮 Loadimage 并在其单击事件中激活从图库中选择图片并将结果返回到 onactivityResult 方法的意图。

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class ImageGalleryDemoActivity extends Activity {


    private static int RESULT_LOAD_IMAGE = 1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }


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

        if (requestCode == RESULT_LOAD_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.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }


    }
}
于 2013-11-08T07:32:22.947 回答