Android - 从图库和相机中选择图像

时间:2014-08-22 16:55:20

标签: android android-intent android-camera android-gallery

我已经搜索过如何从意图中选择相机和图库中的图像。但是,我无法在我的代码中实现它。有人能告诉我如何在我的代码上实现它吗?我很头疼。

这是我的MainActivity.java

public class MainActivity extends Activity implements OnClickListener{

private EditText nama, harga, kondisi, notelepon;

private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;

private String upLoadServerUri = null;
private String imagepath=null;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    nama = (EditText)findViewById(R.id.nama_barang);
    harga = (EditText)findViewById(R.id.harga_barang);
    kondisi = (EditText)findViewById(R.id.kondisi_barang);
    notelepon = (EditText)findViewById(R.id.no_telepon);

    uploadButton = (Button)findViewById(R.id.uploadButton);
    messageText  = (TextView)findViewById(R.id.messageText);
    btnselectpic = (Button)findViewById(R.id.button_selectpic);
    imageview = (ImageView)findViewById(R.id.imageView_pic);


    btnselectpic.setOnClickListener(this);
    uploadButton.setOnClickListener(this);
    upLoadServerUri = "http://192.168.43.226/kambing/UploadToServer.php";
}


@Override
public void onClick(View arg0) {
    if(arg0==btnselectpic)
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
    }
    else if (arg0==uploadButton) {

         dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
         messageText.setText("uploading started.....");
         new Thread(new Runnable() {

             public void run() {

                  uploadFile(imagepath);

             }
           }).start();     
    }

}


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

    if (requestCode == 1 && resultCode == RESULT_OK) {
        //Bitmap photo = (Bitmap) data.getData().getPath(); 

        Uri selectedImageUri = data.getData();
        imagepath = getPath(selectedImageUri);
        Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
        imageview.setImageBitmap(bitmap);
        messageText.setText("Uploading file path:" +imagepath);

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


public int uploadFile(String sourceFileUri) {

      String fileName = sourceFileUri;

      HttpURLConnection conn = null;
      DataOutputStream dos = null;  
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024; 
      File sourceFile = new File(sourceFileUri); 

      if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"+imagepath);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"+ imagepath);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);
               String nm = nama.getText().toString();
               String hrg = harga.getText().toString();
               String knds = kondisi.getText().toString();
               String notlp = notelepon.getText().toString();
               // Open a HTTP  connection to  the URL
               conn = (HttpURLConnection) url.openConnection(); 
               conn.setDoInput(true); // Allow Inputs
               conn.setDoOutput(true); // Allow Outputs
               conn.setUseCaches(false); // Don't use a Cached Copy
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection", "Keep-Alive");
               conn.setRequestProperty("ENCTYPE", "multipart/form-data");
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
               conn.setRequestProperty("uploaded_file", fileName);
               conn.setRequestProperty("uploaded_nama", nm);
               conn.setRequestProperty("uploaded_harga", hrg);
               conn.setRequestProperty("uploaded_kondisi", knds);
               conn.setRequestProperty("uploaded_notelepon", notlp);

               dos = new DataOutputStream(conn.getOutputStream());

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=uploaded_nama" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
               dos.writeBytes(lineEnd);
               dos.writeBytes(nm); // nm is String variable
               dos.writeBytes(lineEnd);

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=uploaded_harga" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
               dos.writeBytes(lineEnd);
               dos.writeBytes(hrg); // nm is String variable
               dos.writeBytes(lineEnd);

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=uploaded_kondisi" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
               dos.writeBytes(lineEnd);
               dos.writeBytes(knds); // nm is String variable
               dos.writeBytes(lineEnd);

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=uploaded_notelepon" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
               dos.writeBytes(lineEnd);
               dos.writeBytes(notlp); // nm is String variable
               dos.writeBytes(lineEnd);

               dos.writeBytes(twoHyphens + boundary + lineEnd); 
               dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                         + fileName + "\"" + lineEnd);

               dos.writeBytes(lineEnd);


               // create a buffer of  maximum size
               bytesAvailable = fileInputStream.available(); 

               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               buffer = new byte[bufferSize];

               // read file and write it into form...
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

               while (bytesRead > 0) {

                 dos.write(buffer, 0, bufferSize);
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                }

               // send multipart form data necesssary after file data...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

               // Responses from the server (code and message)
               serverResponseCode = conn.getResponseCode();
               String serverResponseMessage = conn.getResponseMessage();

               Log.i("uploadFile", "HTTP Response is : " 
                       + serverResponseMessage + ": " + serverResponseCode);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                  +" C:/AppServ/www/kambing/uploads";
                            messageText.setText(msg);
                            Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                            //Intent i = new Intent(MainActivity.this,InputInfo.class);
                            finish();
                            //startActivity(i); 
                        }
                    });                
               }    

               //close the streams //
               fileInputStream.close();
               dos.flush();
               dos.close();

          }

           catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     }
}

3 个答案:

答案 0 :(得分:0)

没有办法同时启动第三方应用程序,我的意思是同时显示他们的用户界面,这没有意义。

但是,您可以按顺序启动它们。当一个Activity完成并且您的onActivityResult()被调用时,从该方法开始另一个Activity

从用户的角度来看,它看起来像是先移动到第二个Activity,然后返回到您的应用。

关于从相机应用程序捕获图像,请查看this示例。 Google为常见意图准备了一些示例,其中使用Camera就是其中之一。

重要的是要了解在启动相机应用程序提供Intent有效URI之前,您需要知道图像的存储位置。另请注意,指向您私人空间的URI需要授予Camera应用程序的权限。

答案 1 :(得分:0)

我也有类似的要求,this link对我很有帮助。 不要忘记添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>到你的清单

答案 2 :(得分:0)

也许你可能对RxPaparazzo感兴趣。这是一个从相机,图库,文件系统中获取图像的库,您可以忘记自己编写代码