简体   繁体   English

如何使用相机捕获图像并将其保存到服务器?

[英]how to capture an image using camera and save it server?

I want to capture an image using camera and store it in server. 我想使用相机捕获图像并将其存储在服务器中。 But I am getting null pointer exception after capturing the image. 但是在捕获图像后,我得到了空指针异常。 Completed mostly but this error is annoying. 大部分已完成,但此错误很烦人。 I am newbie to android i don't know why this error occurs. 我是android的新手,我不知道为什么会发生此错误。 Need help thanks in advance 需要帮助,在此先感谢

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

    if (resultCode == RESULT_OK && requestCode == CAMERA) {

        if (data == null) {
            Snackbar.make(parentView, R.string.string_unable_to_pick_image, Snackbar.LENGTH_INDEFINITE).show();
            return;
        }

        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);


        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP

            Uri tempUri = getImageUri(getApplicationContext(), photo);

            // CALL THIS METHOD TO GET THE ACTUAL PATH

        File finalFile = new File(getRealPathFromURI(tempUri));
            decodeFile(finalFile.toString());}}

**getImageUri method ** ** getImageUri方法**

 public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "aadhar", null);
    return Uri.parse(path);//getting error here
}

getRealPathFromURI Method getRealPathFromURI方法

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

decodeFile Method encodeFile方法

 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 bitmap = BitmapFactory.decodeFile(filePath, o2);

    imageView.setImageBitmap(bitmap);
}

Error 错误

             Caused by: java.lang.NullPointerException: uriString
                  at android.net.Uri$StringUri.<init>(Uri.java:475)
                  at android.net.Uri$StringUri.<init>(Uri.java)
                  at android.net.Uri.parse(Uri.java:437)
                  at com.androidbuts.ui.MainActivity.getImageUri(MainActivity.java:274)
                  at com.androidbuts.ui.MainActivity.onActivityResult(MainActivity.java:233)
                  at android.app.Activity.dispatchActivityResult(Activity.java:7139)
<!--First define permissions in Menifest-->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

// open camera as //将相机打开为

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA);

// Then Retrive image As //然后将图片检索为

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA && data != null) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");

        File imageStorageDir = new File(Environment.getExternalStorageDirectory(),
                getResources().getString(R.string.app_name));
        if (!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }
        imagePath = imageStorageDir + File.separator + "_NAME_YOU_WISH" + ".jpg";
        fileImage = new File(imagePath); // FILE
        try {
            FileOutputStream out = new FileOutputStream(imagePath);
            photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();

            if (fileImage != null) {
                if (fileImage.isFile() && fileImage.exists()) {
                   // MyApplication.log(LOG_TAG, "onActivityResult() SHOWING IMAGE BY GLIDE, fileImage:-> " + fileImage.getAbsolutePath());
                    Glide.with(context)
                            .load(fileImage.getAbsoluteFile())
                            .asBitmap()
                            .placeholder(R.drawable.ic_broken_image)
                            .into(img_camera);
                }
            }

        } catch (Exception e) {
            //MyApplication.log(LOG_TAG, "onActivityResult() , Exception: " + e.getMessage());
        }
    }
}

// CALL THE FUNCTION TO SEND IMAGE TO SERVER //调用将图像发送到服务器的功能

public void callSendCheckReport() {
    MyApplication.showDialog(context, "Please Wait...");

    HashMap<String, Object> map = new HashMap<>();
    map.put("date", today);
    map.put("salesman_id", MyApplication.get_session(MyApplication.SESSION_SALESMAN_ID));

    if (actionStatus.equals("do_CHECK_IN")) {  //// do_CHECK_IN,  do_NO_CHANGE,  do_CHECK_OUT
        map.put("checkin", "yes");
        map.put("in_time", checkTimeStamp);
        if (fileImage != null)
            map.put("in_image", new TypedFile("image*//*", fileImage));
    }

    RestClient.getWebServices().sendCheckReport(map,
            new Callback<String>() {
                @Override
                public void success(String s, Response response) {

                    MyApplication.log(LOG_TAG, "Responce is----> " + s);
                    try {
                        JSONObject res = new JSONObject(s);  // "status":"TRUE","message":"Shop Registered Successfully."}
                        String status = res.getString("status");
                        String message = res.getString("message");

                        MyApplication.stopLoading();
                        if (status.equals("TRUE")) {
                            if (fileImage.exists())
                                fileImage.delete();
                        }
                        showDialogBox(context, getResources().getString(R.string.app_name), message);
                    } catch (JSONException e) {
                        MyApplication.stopLoading();
                       // MyApplication.log(LOG_TAG + "RESPONSE JSONException  ->" + e.getMessage());
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    MyApplication.log(LOG_TAG + " RetrofitError  ->" + error.getMessage());
                    MyApplication.stopLoading();
                }
            });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM