private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data");
WebView webView = findViewById(R.id.webview);
webView.loadUrl("javascript:loadImage('" + encodeToBase64(imageBitmap) + "')");
}
}
function loadImage(data) { var img = document.createElement('img'); img.setAttribute('src', 'data:image/jpeg;base64,' + data); document.body.appendChild(img); }
其中,encodeToBase64是将Bitmap转换为Base64编码字符串的辅助方法:
private String encodeToBase64(Bitmap imageBitmap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); byte[] imageBytes = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}