无法使用相机android获取图像

时间:2017-06-21 13:36:19

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

应用程序应该从Camera或Gallery(用户选择)获取图像,然后将其上传到服务器。 从库中获取图像并将其上传到服务器没有问题。 这里的问题是检索相机拍摄的图像!

public class UploadActivity extends AppCompatActivity implements View.OnClickListener {

private Button UploadBn;
private ImageButton ChooseBn, CameraBn;
private EditText NAME;
private ImageView imgView;
private CameraPhoto cameraPhoto;
private GalleryPhoto galleryPhoto;
final int CAMERA_REQUEST=13323;
final int GALLERY_REQUEST=22131;
private String selectedPhoto;
private Bitmap bitmap = null;
private String UploadUrl="http://localhost/webapp/getImg.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    NAME=(EditText)findViewById(R.id.name);
    UploadBn=(Button)findViewById(R.id.uploadBn);
    ChooseBn=(ImageButton) findViewById(R.id.ivGallery);
    CameraBn=(ImageButton) findViewById(R.id.ivCamera);
    imgView=(ImageView)findViewById(R.id.imageView);
    cameraPhoto = new CameraPhoto(getApplicationContext());
    galleryPhoto = new GalleryPhoto(getApplicationContext());
    ChooseBn.setOnClickListener(this);
    UploadBn.setOnClickListener(this);
    CameraBn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.ivGallery:
                selectImageGalerie();
            break;

        case R.id.uploadBn:
            if(NAME==null || imgView.getDrawable()==null)
                Toast.makeText(this,"select an image, give it a name",Toast.LENGTH_LONG).show();
            else
                uploadImage();
            break;
        case R.id.ivCamera:
            selectImageCamera();
            break;
    }
}

private void selectImageGalerie() {

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent,GALLERY_REQUEST);
}

private void selectImageCamera() {
    try {
        startActivityForResult(cameraPhoto.takePhotoIntent(), CAMERA_REQUEST);
        cameraPhoto.addToGallery();
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Somathing Wrong while taking photos", Toast.LENGTH_SHORT).show();
    }
}

private String imageToString(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
    byte[] imgBytes=byteArrayOutputStream.toByteArray();
    return Base64.encodeToString(imgBytes, Base64.DEFAULT);
}

private void uploadImage() {
    final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
    StringRequest stringRequest=new StringRequest(Request.Method.POST, UploadUrl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            Toast.makeText(UploadActivity.this, response , Toast.LENGTH_LONG).show();
            imgView.setImageResource(0);
            imgView.setVisibility(View.GONE);
            NAME.setText("");
            NAME.setVisibility(View.GONE);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            loading.dismiss();
            Toast.makeText(UploadActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
        }
    })
    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params=new HashMap<>();
            params.put("name",NAME.getText().toString().trim()+".jpg");
            params.put("encoded",imageToString(bitmap));
            return params;
        }
    };
    MySingleton.getInstance(UploadActivity.this).addToRequestQue(stringRequest);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode==RESULT_OK && data != null){
        if(requestCode==GALLERY_REQUEST) {
            Uri path = data.getData();
            galleryPhoto.setPhotoUri(path);
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(requestCode==CAMERA_REQUEST) {
                String photoPath=cameraPhoto.getPhotoPath();
                selectedPhoto=photoPath;
            try {
                    Log.d("BITMAP ==", "AWEL EL TRY");
                    bitmap= ImageLoader.init().from(photoPath).requestSize(300,300).getBitmap();
                    imgView.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    Toast.makeText(getApplicationContext(),"Something Wrong while choosing photos",Toast.LENGTH_SHORT).show();
                }
            }
        imgView.setImageBitmap(bitmap);
        imgView.setVisibility(View.VISIBLE);
        NAME.setVisibility(View.VISIBLE);
        Log.d("BITMAP ==", "E5ER EL TRY");
    }
}

}

执行一些测试后,我发现变量 data null 所以它会跳过 if()中的所有语句em> onActivityResult()方法。 它没有意义,即使我拍了照片,为什么相机不会返回值!

2 个答案:

答案 0 :(得分:2)

  

即使我拍了照片,为什么相机也不会返回值

如果您在EXTRA_OUTPUT上提供IntentACTION_IMAGE_CAPTURE则无需返回结果。我认为那是takePhotoIntent()的作用。

此外,requestCode==CAMERA_REQUEST分支的其余代码仍未使用data Uri

答案 1 :(得分:0)

  

您好快速修复尝试提供的代码并进行更深入的学习阅读此https://developer.android.com/training/camera/photobasics.html

在R.id.uploadBn按钮上单击调用captureImage()方法而不是selectImageCamera()。

 private Uri fileUri; // file url to store image/video
 public static final int MEDIA_TYPE_IMAGE = 1;
  private static final String IMAGE_DIRECTORY_NAME = "MyPhotos";
  

捕获相机图像将照相机应用程序请求图像捕获

private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
  

创建文件uri以存储图像/视频

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}
  

返回图片

private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }



// Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");

    }
    return mediaFile;
}
  

关闭后将调用接收活动结果方法   相机

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // successfully captured the image
             previewCapturedImage();

        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}
  

从ImageView路径显示图像

private void previewCapturedImage() {
    try {

        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        imgView.setImageBitmap(bitmap);
    } catch (NullPointerException e) {
        e.printStackTrace();
    }