当前位置: 首页 > 知识库问答 >
问题:

如何将捕获的图像导入应用程序并希望上载到服务器?

臧友樵
2023-03-14

我试着用相机拍摄一幅图像,并在我的应用程序中将其设置为个人资料图片。

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

当通过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个答案

通京
2023-03-14

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

颜河
2023-03-14

点击按钮打开相机

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

私人文件picfile

@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);

你必须使用这些LIBhttp://www.java2s.com/Code/Jar/h/Downloadhttpmime401jar.htm

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

 类似资料:
  • 我在我的屏幕上有四个图像视图,从相机中捕获图像并显示在其中,现在我想将这些图像上传到服务器上。因此,我使用了下面的代码来获取它们的路径,但它通过了异常。是否有可能从摄像机拍摄的图像视图将图像上传到服务器(无需将图像存储到内存中)。

  • 我正在尝试用相机拍照并上传到Firebase。我使用AlertDialog询问用户是否想要使用相机或从图库中选择图像。我可以用相机拍照,但是当我试图上传图像时,它说找不到图像。 以下是我的图像选择方法: 下面是我上传图片的方法: 提前感谢任何帮助的朋友。

  • 我想上传图像/文件到服务器使用它的uri使用下面的代码 所以,在这里我的回应是不成功的。API返回我内部服务器错误状态500,但我知道服务器工作良好(我测试了其他应用程序)。另外,文件uri也可以。我是新来的,所以能有人发现我的错误,并详细解释为什么是错误的。

  • 本文向大家介绍页面以HTML构建,并希望加载到SAPUI5应用程序的JS视图中。,包括了页面以HTML构建,并希望加载到SAPUI5应用程序的JS视图中。的使用技巧和注意事项,需要的朋友参考一下 最常用的方法是将HTML页面作为iframe嵌入。这是例子。 也可以使用AJAX调用来加载它,也可以使用sap.ui.core.HTML来显示它,但这取决于您的HTML页面。

  • 问题内容: 当我单击a时,它会打开相机,并在保存时将其保存到图库中。我想在新活动中将该图片显示为。 这是我对相机按钮单击的代码 问题答案: 您的主要活动 在您的Activity2上,在onCreate方法上编写此代码

  • 我们正在通过插件在EA中自动创建需求元素。但问题是我们无法将图像从目录导入到图像管理器,并将超链接添加到Requirement元素Notes。那么Enterprise architect是否提供了API来将映像从目录导入到映像管理器,并将超链接添加到Requirement元素注释中。