2014-12-05 110 views
0

我想將圖像上傳到我的amazon s3服務器。 要做到這一點,我需要做我想送,但圖像的文件不知它不工作:創建圖像文件,android

按鈕選擇圖像:

//When clicked on addimage 
     addImage.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // To open up a gallery browser 
       Intent intent = new Intent(); 
       intent.setType("image/*"); 
       intent.setAction(Intent.ACTION_GET_CONTENT); 
       startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE); 
      } 

當圖庫圖像上點擊:

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

    if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK && null != data) { 
     urimg = data.getData(); 

     String path = getPath(urimg); 
     //create file of image to upload 
     images3 = new File(path); 
    } 
} 
     }); 

的方法的getPath:

public String getPath(Uri uri) { 
     if(uri == null) { 
      return null; 
     } 
     String[] projection = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null); 
     if(cursor != null){ 
      int column_index = cursor 
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      cursor.moveToFirst(); 
      return cursor.getString(column_index); 
     } 
     return uri.getPath(); 
    } 

我得到這個錯誤:

12-05 01:37:13.857 30611-30611/com.laurenswuyts.witpa E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    Process: com.laurenswuyts.witpa, PID: 30611 
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:3000 flg=0x1 }} to activity {com.laurenswuyts.witpa/com.laurenswuyts.witpa.Activities.Events.AddEventActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference 
      at android.app.ActivityThread.deliverResults(ActivityThread.java:3539) 
      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582) 
      at android.app.ActivityThread.access$1300(ActivityThread.java:144) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:135) 
      at android.app.ActivityThread.main(ActivityThread.java:5221) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:372) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference 
      at java.io.File.fixSlashes(File.java:185) 
      at java.io.File.<init>(File.java:134) 

回答

0

使用這個類來保存圖像時,任何你想將其保存

import java.io.FileOutputStream; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.Bitmap.Config; 
import android.graphics.Canvas; 
import android.graphics.drawable.BitmapDrawable; 
import android.graphics.drawable.Drawable; 
import android.os.Environment; 
import android.util.Log; 

public class SaveImageIntoDrawable { 

    public static String savedImagePath = "" ; 

    public static Bitmap drawableToBitmap (Drawable drawable) { 
     if (drawable instanceof BitmapDrawable) { 
      return ((BitmapDrawable)drawable).getBitmap(); 
     } 

     Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); 
     Canvas canvas = new Canvas(bitmap); 
     drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 
     drawable.draw(canvas); 

     return bitmap; 
    } 

    public static void saveBitmapIntoDrawable(Bitmap bitmap, Context object) { 
     try { 

      String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date()); 

      savedImagePath = Environment.getExternalStorageDirectory() + "/imagename"+timeStamp+".png" ; 

      FileOutputStream out = new FileOutputStream(savedImagePath); 
      Log.i(object.getFilesDir().getAbsolutePath(), "complete-path"); 

      bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); 
      out.close(); 
     } catch (Exception err) { 
      err.printStackTrace(); 
      Log.i("Error in SaveImageIntoDrawable ", "Error"); 
     } 
    } 
} 

,並使用這個類來發表您的圖像:

import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.ArrayList; 
import java.util.Dictionary; 
import java.util.Enumeration; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.BufferedHttpEntity; 
import org.apache.http.entity.mime.HttpMultipartMode; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONObject; 

import android.app.ProgressDialog; 
import android.content.Context; 
import android.os.AsyncTask; 
import android.util.Log; 

import com.secondhandbooks.util.ConvertStreamIntoString; 
import com.secondhandbooks.util.SaveImageIntoDrawable; 

public abstract class BaseAsync_Post extends AsyncTask<String, String, InputStream> 
{ 

    Context context ; 
    private HttpPost httppost; 
    String url ; 
    Dictionary<String, String> dictionary ; 


    public BaseAsync_Post(String url , Dictionary<String, String> dictionary, Context context) { 
     this.url = url ; 
     this.dictionary = dictionary; 
     this.context = context ; 

     Enumeration<String> enumeration = dictionary.keys() ; 


     showLogs("constructor") ; 

     while (enumeration.hasMoreElements()) 
     { 
      showLogs(enumeration.nextElement()) ; 
     } 
    } 

    @Override 
    abstract protected void onPreExecute() ; 
    @Override 
    abstract protected void onPostExecute(InputStream result) ; 

    @Override 
    protected InputStream doInBackground(String... params) { 
     // TODO Auto-generated method stub 
     // TODO Auto-generated method stub 
     InputStream is = null; 

     HttpClient httpclient = new DefaultHttpClient(); 

     httppost = new HttpPost(url); 

     MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

     try 
     { 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(50); 

      Enumeration<String> enumeration = dictionary.keys() ; 

      while (enumeration.hasMoreElements()) 
      { 
       String key = enumeration.nextElement() ; 

       if (key.equals("file")) 
       { 
        final File file = new File(SaveImageIntoDrawable.savedImagePath); 

        if (file.isFile()) 
        { 
         showLogs("is file"); 
        } 
        else 
        { 
         showLogs("no-file"); 
        } 

        FileBody fb = new FileBody(file); 
        entity.addPart(key, fb);       
       } 
       else 
       { 
        entity.addPart(key, new StringBody(dictionary.get(key))); 
       } 
      } 

      httppost.setEntity(entity); 

      HttpResponse response = httpclient.execute(httppost); 

      HttpEntity entity1 = response.getEntity(); 

      BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity1); 

      is = bufHttpEntity.getContent(); 

     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
      showLogs("ClientProtocolException"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      showLogs("IOException"); 
     } 

     return is; 
    } 

    public String getString(JSONObject json, String TAG) { 
     String returnParseData = ""; 

     try { 
      Object aObj = json.get(TAG); 
      if (aObj instanceof Boolean) { 
       returnParseData = Boolean.toString(json.getBoolean(TAG)); 
      } else if (aObj instanceof Integer) { 
       returnParseData = Integer.toString(json.getInt(TAG)); 
      } else if (aObj instanceof String) { 
       returnParseData = json.getString(TAG); 
      } else { 
       returnParseData = json.getString(TAG); 
      } 
     } catch (Exception err) { 
      err.printStackTrace(); 
      returnParseData = ""; 
     } 

     return returnParseData; 
    } 

    public String getIntintoString(JSONObject json, String TAG) { 
     int returnParseData = -1; 

     try { 
      returnParseData = json.getInt(TAG) ; 
     } catch (Exception err) { 
      err.printStackTrace(); 
      returnParseData = -1; 
     } 

     return Integer.toString(returnParseData) ; 
    } 

    public void showLogs (String msg) 
    { 
     Log.e("HTTP-POST", msg) ; 
    } 

} 

,並從那裏下載httpmime包:http://www.java2s.com/Code/Jar/h/Downloadhttpmime42jar.htm