【发布时间】:2020-02-05 15:31:28
【问题描述】:
按钮单击以打开相机,拍照并尝试将所选图片转换为 base64 字符串,但无法正常工作。请检查以下代码。
private static final int CAMERA_PIC_REQUEST = 1337;
Button upload;
@Override
protected void onCreate(Bundle savedInstanceState) {
upload = findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageview = (ImageView) findViewById(R.id.uploadimage);
imageview.setImageBitmap(image);
String directoryPath = Environment.getExternalStorageDirectory() + "/";
String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".png";
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
System.out.print(filePath);
System.out.print(Uri.fromFile( new File(filePath) ));
File imageFile = new File(filePath);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image1 = stream.toByteArray();
String img_str = Base64.encodeToString(image1, 0);
}
我使用下面的代码将静态图像转换为base64字符串,但我想拍照并转换为base64字符串。
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.testimage);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.PNG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
System.out.print(ba1);
【问题讨论】: