【问题标题】:cannot fetch images using camera android无法使用相机 android 获取图像
【发布时间】:2017-06-21 13:36:19
【问题描述】:

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

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

}

在进行了一些测试后,我发现变量 datanull 所以它跳过了 if() 中的所有语句em>onActivityResult() 方法。 说不通,为什么我拍了照片相机也不返回值!

【问题讨论】:

  • 详细说明,“问题”是什么。
  • 在安卓应用程序中尝试检索用相机拍摄的照片时,我可以访问相机并拍摄。但是,当意图返回到 onActivityResult() 时,一个名为 imgView 的 imageView 应该显示该图像。真正发生了什么,活动保持不变并且没有更新我编辑了帖子再次检查。
  • 你好,你能告诉我你在 takePhotoIntent() 方法中写了什么吗?
  • @nishon:我在关注tutorial时下载的库中无法使用它的方法

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


【解决方案1】:

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

如果您在Intent 上提供EXTRA_OUTPUT,则ACTION_IMAGE_CAPTURE 不需要返回结果。我认为这就是 takePhotoIntent() 所做的。

此外,requestCode==CAMERA_REQUEST 分支的其余代码无论如何都不会使用 data Uri

【讨论】:

    【解决方案2】:

    您好,要快速修复,请尝试提供的代码,如需更深入的学习,请阅读此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";
    

    Capturing Camera Image 将启动相机应用请求图像捕获

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

    【讨论】:

    • 我用 getOutputMediaFileUri() 和 getOutputMediaFile() 更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    相关资源
    最近更新 更多