简体   繁体   中英

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. 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.

       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.
  2. Convert the picture to base64 String.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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