简体   繁体   English

在 Android (Java) 中将选定的图像转换为 base64 字符串

[英]Convert selected image into base64 string in Android (Java)

Button click to open camera, take picture and tried to convert that selected picture to base64 string but not working.按钮单击打开相机,拍照并尝试将所选图片转换为 base64 字符串但不起作用。 please check below code.请检查下面的代码。

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

I worked below code for convert static image into base64 string, but i want to take picture and convert to base64 string.我在下面的代码中将静态图像转换为 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);

Please follow this to get actual image.请按照获取实际图像。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
     {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
           Bitmap photo = (Bitmap) data.getExtras().get("data");
           String imgString = toBase64(photo);
          }
     }

public String toBase64(Bitmap bm) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();

    return Base64.encodeToString(b, Base64.NO_WRAP);
}

What I understand is, you need to do two things with the taken picture:我的理解是,你需要对拍摄的照片做两件事:

  1. Show the picture in imageView.在 imageView 中显示图片。
  2. Convert the picture to base64 String.将图片转换为 base64 字符串。

To do these two things, you don't need to write the Picture to file at your own code.要做这两件事,你不需要在你自己的代码中编写图片文件。 You have already the bitmap from the camera using the following code:您已经使用以下代码获得了来自相机的位图:

Bitmap pictureFromCamera = (Bitmap) data.getExtras().get("data");

Now just show it in the imageView using现在只需使用

imageView.setImageBitmap(pictureFromCamera)

To convert it to base64, just convert the pictureFromCamera to base64 like要将其转换为 base64,只需将pictureFromCamera转换为 base64 即可

String base64StringOfCameraPic = getBase64StringFromBitmap(pictureFromCamera , 100)

String getBase64StringFromBitmap(Bitmap bitmap, int quality)
{
    if (bitmap == null || quality < 0)
    {
        return null;
    } else
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, quality, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM