如何将捕获的图像导入应用程序并想要上传到服务器?

时间:2014-08-05 09:50:17

标签: java android

我尝试通过使用相机来捕获图像并将其设置为我的应用中的个人资料图片。

相机会捕捉图像,但在配置文件中没有设置任何图片,仍为空白,并希望将该图片上传到我的服务器。

在通过DataInputStream读取图片时,它说,“不推荐使用DataInputStream类型的方法readLine()”

帮我解决这个问题。

这是我的代码:

    public void settings(){

                AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(SignUp.this);

                alertDialog2.setTitle("");

                alertDialog2.setMessage("Please select an image..");

                alertDialog2.setIcon(R.drawable.act_camera);

                alertDialog2.setPositiveButton("CAMERA.",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                condition="from_camera";
                                pd = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
                                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);            
                                startActivityForResult(cameraIntent, CAM_REQUREST);     
                            }
                        });

                        alertDialog2.setNegativeButton("GALLERY.",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                condition="from_gallery";
                                pd = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
                                Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                                startActivityForResult(i, RESULT_LOAD_IMAGE);


                            }
                        });

                alertDialog2.show();

                                } 

            @JavascriptInterface

        public void showCustomAlert() {
            // TODO Auto-generated method stub


             Context context = getApplicationContext();
                // Create layout inflator object to inflate toast.xml file
                LayoutInflater inflater = getLayoutInflater();

                // Call toast.xml file for toast layout 
                View toastRoot = inflater.inflate(R.layout.toast, null);

                Toast toast = new Toast(context);

                // Set layout to toast 
                toast.setView(toastRoot);
                toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
                        0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.show();




        }

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

           if (requestCode == CAM_REQUREST) 
           {  
               bitmap_profile_image = (Bitmap) data.getExtras().get("data");  
               imagepath =  ImageWrite(bitmap_profile_image); 
               pd.dismiss();
           } 

         else 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);
               Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
               cursor.close();
               john.setImageBitmap(thumbnail); 
               System.out.println("Step--------->1");
               pd1 = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
               System.out.println("Step--------->1");
               imagepath =  ImageWrite(thumbnail);
               pd1.dismiss();
               pd.dismiss();
               Log.w("path of image from gallery......*******.....", picturePath+"");


           } 
         else{


         }    

           Imageuploading();  


          }

        public String ImageWrite(Bitmap bitmap1)
        {
            //pd = ProgressDialog.show(context,null, "Please wait...",true);
             String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
                OutputStream outStream = null;
                File file = new File(extStorageDirectory, "slectimage.PNG");

                try 
                {

                    outStream = new FileOutputStream(file);
                    bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                    pd.dismiss();


                } 
                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                    pd.dismiss();

                } catch (IOException e) 
                {
                    e.printStackTrace();
                    pd.dismiss();

                }
                String imageInSD = "/sdcard/slectimage.PNG";
            pd.dismiss();
                return imageInSD;

        }

        protected void Imageuploading() {
            // TODO Auto-generated method stub
            pd1 = ProgressDialog.show(this,null, "Please wait...",true);
             try{


                    Log.e("SANGUUU", "dfdf");

                    HttpURLConnection connection = null;
                    DataOutputStream outputStream = null;
                    String pathToOurFile = (String) imagepath; 
                    System.out.println("patho our file"+pathToOurFile);
                    //String urlServer = "http://demo.cogzideltemplates.com/client/snapchat-clone/index.php/user/image_upload";
                    String urlServer = "http://demo.cogzidel.com/sedio/mobile/image_upload";
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary =  "*****";

                    int bytesRead, bytesAvailable, bufferSize;
                    byte[] buffer;
                    int maxBufferSize = 1*1024*1024;

                    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

                    URL url = new URL(urlServer);
                    connection = (HttpURLConnection) url.openConnection();

                    // Allow Inputs & Outputs
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);

                    // Enable POST method
                    connection.setRequestMethod("POST");

                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                    outputStream = new DataOutputStream( connection.getOutputStream() );
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
                    outputStream.writeBytes(lineEnd);

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

                    // Read file
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while (bytesRead > 0)
                    {
                        System.out.println("test");
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }

                    outputStream.writeBytes(lineEnd);
                    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                    connection.getResponseCode();
                    String serverResponseMessage = connection.getResponseMessage();
                    URL serverResponseMessage1 = connection.getURL();
                    System.out.println("url value"+serverResponseMessage1);
                    connection.getResponseMessage();
                //  Toast.makeText(getApplicationContext(),  serverResponseMessage, Toast.LENGTH_LONG).show();
                    System.out.println("image"+serverResponseMessage);
                    int len=connection.getContentLength();
                    System.out.println("Length of url--->1"+len);                
                    fileInputStream.close();
                    outputStream.flush();
                    outputStream.close();

                    DataInputStream inputStream1 = null;
                    inputStream1 = new DataInputStream (connection.getInputStream());
                    String str="";
                    String Str1_imageurl="";

                    while ((  str = inputStream1.readLine()) != null)  // here getting deprecated error
                    {
                       Log.e("Debug","Server Response "+str);

                        Str1_imageurl = str;
                        Log.e("Debug","Server Response String imageurl"+str);
                    }
                    inputStream1.close();
                    System.out.println("image url"+Str1_imageurl);
            //      Toast.makeText(getApplicationContext(),  Str1_imageurl, Toast.LENGTH_LONG).show();
                    pd1.dismiss();
                       stry=Str1_imageurl.trim();


                         }
                         catch(Exception e){

                                e.printStackTrace();

                         }

        }

     //create helping method cropCapturedImage(Uri picUri)
     public void cropCapturedImage(Uri picUri){
      //call the standard crop action intent
      Intent cropIntent = new Intent("com.android.camera.action.CROP");
      //indicate image type and Uri of image
      cropIntent.setDataAndType(picUri, "image/*");
      //set crop properties
      cropIntent.putExtra("crop", "true");
      //indicate aspect of desired crop
      cropIntent.putExtra("aspectX", 1);
      cropIntent.putExtra("aspectY", 1);
      //indicate output X and Y
      cropIntent.putExtra("outputX", 256);
      cropIntent.putExtra("outputY", 256);
      //retrieve data on return
      cropIntent.putExtra("return-data", true);
      //start the activity - we handle returning in onActivityResult
      startActivityForResult(cropIntent, 2);
     }

2 个答案:

答案 0 :(得分:2)

点击按钮打开相机

    //  Util.TEMP_PHOTO_FILE_NAME is String file name ; 

            String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mFileTemp = new File(Environment
                    .getExternalStorageDirectory(),
                    Util.TEMP_PHOTO_FILE_NAME);
        } else {
            mFileTemp = new File(getApplicationContext().getFilesDir(),
                    Util.TEMP_PHOTO_FILE_NAME);
        }
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        try {
            Uri mImageCaptureUri = null;
            // String state = Environment.getExternalStorageState();
            if (mFileTemp == null) {
                System.out.println("no file found");
            } else {
                System.out.println("file found");

            }
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                mImageCaptureUri = Uri.fromFile(mFileTemp);
            } else {
                mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
            }
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                    mImageCaptureUri);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, SELECT_CAMERA_IMAGE_REQUEST);
            /*
             * Intent cameraIntent = new
             * Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
             * startActivityForResult(cameraIntent,
             * SELECT_CAMERA_IMAGE_REQUEST);
             */
        } catch (ActivityNotFoundException e) {

            Log.d("Tag", "cannot take picture", e);
        }

onActivityResult:       私人文件图片文件;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
      if (requestCode == SELECT_CAMERA_IMAGE_REQUEST
                && resultCode == Activity.RESULT_OK) {
            picfile = mFileTemp;
            postFlagFileCheck = 1;
            bitmap_postImage = BitmapFactory.decodeFile(picfile
                    .getAbsolutePath());
            setImagePreview(bitmap_postImage);
        }
  }

将该图像文件发送到服务器

        HttpClient httpclient;
        httpclient = HttpClientSingalTon.getHttpClienttest();
        HttpPost httpPostRequest = new HttpPost(URL);
        // Try This
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(yourimagefile, "image/jpeg");
        mpEntity.addPart("file", cbFile); 
        httpPostRequest.setEntity(mpEntity);
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
你必须使用这些库 http://www.java2s.com/Code/Jar/h/Downloadhttpmime401jar.htm

http://www.java2s.com/Code/Jar/a/Downloadapachemime4j06jar.htm

答案 1 :(得分:0)

如果您能够获取图像的路径,那么尝试从该路径获取图像。 有一种替代方法可以在服务器上上传图像。您可以使用Base64编码将图像转换为Sting,并通过JSON将该字符串发送到您的服务器。