2014-09-25 27 views
0

我在Android新我想從畫廊中選擇圖像,並希望裁剪和發送服務器。 當我從庫中選擇圖像,發送給服務器。它的成功與上傳 時,我想用農作物的方法......然後..Image開放,當我裁剪,然後點擊確定..then我的應用程序停止不幸如何裁剪圖像從gallary和uploade到服務器

請告訴我,即時通訊做錯了 這裏是我的整個代碼活動

public class MainActivity extends Activity { 

private ImageView image; 
private Button uploadButton; 
private Bitmap bitmap; 
private Button selectImageButton; 
ByteArrayBody   bab1 = null; 
Uri selectedImge; 
// number of images to select 
private static final int PICK_IMAGE = 1; 

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

    // on click select an image 
    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(); 
    } 
    }); 
} 

/** 
    * 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.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    intent.setType("image/*"); 
// intent.setAction(Intent.ACTION_GET_CONTENT); 
    intent.putExtra("crop", "true"); 
    intent.putExtra("outputX", 200); 
    intent.putExtra("outputY", 200); 
    intent.putExtra("aspectX", 1); 
    intent.putExtra("aspectY", 1); 
    intent.putExtra("scale", true); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImge); 
    intent.putExtra("outputFormat", 

    Bitmap.CompressFormat.JPEG.toString()); 


    // intent.putExtra("return-data", true); 
     startActivityForResult(intent, 
       PICK_IMAGE); 
} 



/* 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) { 
    selectedImge = data.getData(); 
    String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

    Cursor cursor = getContentResolver().query(selectedImge, 
    filePathColumn, null, null, null); 
    cursor.moveToFirst(); 

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

    decodeFile(picturePath); 

    } 
} 

/** 
    * The method decodes the image file to avoid out of memory issues. Sets the 
    * selected image in to the ImageView. 
    * 
    * @param filePath 
    */ 
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> { 
    private String webAddressToPost = "http://your-website-here.com"; 

    // private ProgressDialog dialog; 
    private ProgressDialog dialog = new ProgressDialog(MainActivity.this); 

    @Override 
    protected void onPreExecute() { 
    dialog.setMessage("Uploading..."); 
    dialog.show(); 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
    try { 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpContext localContext = new BasicHttpContext(); 
    HttpPost httpPost = new HttpPost("http://www.your domain.com/signup"); 

    MultipartEntity entity = new MultipartEntity(
     HttpMultipartMode.BROWSER_COMPATIBLE); 

    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    bitmap.compress(CompressFormat.JPEG, 75, bos); 
    byte[] data = bos.toByteArray(); 
    // byte[] image=Base64.encode(data, Base64.DEFAULT); 
    bab1 = new ByteArrayBody(data, "profile.jpg"); 
    // 


    entity.addPart("fullName", new StringBody("sammywaseem")); 
    entity.addPart("userName", new StringBody("samm")); 
    entity.addPart("dob", new StringBody("2014-09-09")); 
    entity.addPart("age", new StringBody("18")); 
    entity.addPart("gender", new StringBody("M")); 
    entity.addPart("interestIn", new StringBody("Both")); 
    entity.addPart("toMeet", new StringBody("Women")); 
    entity.addPart("email", new StringBody("[email protected]")); 
    entity.addPart("pwd", new StringBody("123456")); 

    entity.addPart("latitude", new StringBody("38.56525803")); 
    entity.addPart("longitude", new StringBody("71.98562622")); 
    if (bab1 != null) { 
     entity.addPart("uploaded_file", bab1); 
    } 



    httpPost.setEntity(entity); 
    HttpResponse response = httpClient.execute(httpPost, 
     localContext); 
    BufferedReader reader = new BufferedReader(
     new InputStreamReader(
     response.getEntity().getContent(), "UTF-8")); 

    String sResponse = reader.readLine(); 
    return sResponse; 
    } catch (Exception e) { 
    // something went wrong. connection with the server error 
    } 
    return null; 
    } 

    @Override 
    protected void onPostExecute(String result) 
    { 
    dialog.dismiss(); 
    Toast.makeText(getApplicationContext(), "file uploaded", 
    Toast.LENGTH_LONG).show(); 
    } 

} 

} 

這裏是我的logcat錯誤

09-25 11:36:58.719: E/AndroidRuntime(27221): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.upload_image/com.example.upload_image.MainActivity}: java.lang.NullPointerException 
09-25 11:36:58.719: E/AndroidRuntime(27221): at android.app.ActivityThread.deliverResults(ActivityThread.java:3149) 
09-25 11:36:58.719: E/AndroidRuntime(27221): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3192) 
09-25 11:36:58.719: E/AndroidRuntime(27221): Caused by: java.lang.NullPointerException 
09-25 11:36:58.719: E/AndroidRuntime(27221): at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1094) 
09-25 11:36:58.719: E/AndroidRuntime(27221): at android.content.ContentResolver.query(ContentResolver.java:354) 
+0

轉到行號這個地方正在發生'產生的原因:java.lang中.NullPointerException' – 2014-09-25 06:13:18

+0

Rahul Cursor cursor = getContentResolver()。query(selectedImge, filePathColumn,null,null,null); – 2014-09-25 06:31:35

+0

所以你的遊標實例返回null。將這段代碼放在try catch塊的這一行下面,或者對遊標進行空的檢查 – 2014-09-25 06:34:42

回答

0

可能是你的意圖是返回null數據試試這個。 ...您的selectImagefromGallery

Intent intent = new Intent(Intent.ACTION_PICK, 
    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
startActivityForResult(intent, 2);` 

和OnActivityResult

if (requestCode == 2) { 
    Uri picUri = data.getData(); 
    System.out.println("picUri-----" +picUri); 
    String path = getRealPathFromUri(getActivity(), picUri); 
    System.out.println("PATH-----" +path); 

解決的ImagePath使用

public String getRealPathFromUri(Context context, Uri contentUri) { 
    Cursor cursor = null; 
    try{ 
      String[] proj = { MediaStore.Images.Media.DATA }; 
      cursor = context.getContentResolver().query(contentUri, proj, null, null, null); 
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      cursor.moveToFirst(); 
      return cursor.getString(column_index); 
     } 
     finally { 
      if (cursor != null) { 
       cursor.close(); 
      } 
     } 
} 

要上傳文件中添加部分爲您multipartentity

File uploadFile1 = new File(path); 
multipart.addFilePart("photo1", uploadFile1); 
0
intent = new Intent(); 
      intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

========== Web服務的例子很多

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

    super.onActivityResult(requestCode, resultCode, data); 

    if (resultCode == RESULT_OK) { 
     if (requestCode == PICK_FROM_FILE) { 
      // get the Uri for the captured image 
      uri = data.getData(); 

      String[] prjection ={MediaStore.Images.Media.DATA}; 
      Cursor cursor = getContentResolver().query(uri,prjection,null,null,null); 
      cursor.moveToFirst(); 
      int columnIndex = cursor.getColumnIndex(prjection[0]); 
      ImagePath = cursor.getString(columnIndex); 
      cursor.close(); 
      FixBitmap = BitmapFactory.decodeFile(ImagePath); 
      //ShowSelectedImage = (ImageView)findViewById(R.id.imageView); 
      // FixBitmap = new BitmapDrawable(ImagePath); 


      ShowSelectedImage = (ImageView)findViewById(R.id.imageView); 

      int nh = (int) (FixBitmap.getHeight() * (512.0/FixBitmap.getWidth())); 
      FixBitmap = Bitmap.createScaledBitmap(FixBitmap, 512, nh, true); 

      ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath)); 
      // ShowSelectedImage.setImageBitmap(FixBitmap); 
      performCrop(); 
     } 
     // user is returning from cropping the image 
     else if (requestCode == CROP_PIC) { 
      // get the returned data 

      Bundle extras = data.getExtras(); 
      // get the cropped bitmap 
      thePic = extras.getParcelable("data"); 

      ShowSelectedImage = (ImageView)findViewById(R.id.imageView); 


      ShowSelectedImage.setImageBitmap(thePic); 
      //ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath)); 
      // ShowSelectedImage.setImageBitmap(FixBitmap); 
     } 
    } 

} 
    private void performCrop() { 
     // take care of exceptions 
     try { 
      // call the standard crop action intent (the user device may not 
      // support it) 
      cropIntent = new Intent("com.android.camera.action.CROP"); 
      // indicate image type and Uri 
      cropIntent.setDataAndType(uri, "image/*"); 
      // set crop properties 
      cropIntent.putExtra("crop", "true"); 
      cropIntent.putExtra("scale", true); 
      // indicate aspect of desired crop 
      cropIntent.putExtra("aspectX", 1); 
      cropIntent.putExtra("aspectY", 1); 
      // indicate output X and Y 
      cropIntent.putExtra("outputX", 150); 
      cropIntent.putExtra("outputY", 100); 
      // retrieve data on return 
      cropIntent.putExtra("return-data", true); 
      // start the activity - we handle returning in onActivityResult 
      startActivityForResult(cropIntent, CROP_PIC); 
     } 
     // respond to users whose devices do not support the crop action 
     catch (ActivityNotFoundException anfe) { 
      Toast toast = Toast 
        .makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT); 
      toast.show(); 
     } 
    }