首先,我们需要使用Camera API来拍摄照片并将其保存到设备的存储空间中,然后我们可以使用FileProvider来获取照片的URI,以及将它加载到Webview中。以下是具体的代码实现:
private static final int REQUEST_IMAGE_CAPTURE = 1;
private Uri imageUri;
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onShowFileChooser(
WebView webView,
ValueCallback filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
// 创建一个文件
File imageFile = null;
try {
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
imageFile = File.createTempFile(
imageFileName, /* 前缀 */
".jpg", /* 后缀 */
storageDir /* 目录 */
);
} catch (IOException ex) { }
// 使用FileProvider获取照片的URI
imageUri = FileProvider.getUriForFile(
MainActivity.this,
"com.example.yourpackagename.provider",
imageFile);
// 启动相机应用
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
return true;
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// 将照片加载到Webview中
webView.loadUrl("javascript:loadImage('" + imageUri.toString() + "')");
}
}
function loadImage(imageUrl) {
var img = document.createElement("img");
img.src = imageUrl;
document.getElementById("photo").appendChild(img);
}
这样,我们就可以通过拍照获取照片,并将其实时加载到Webview中了。