Search code examples
androidbase64android-imageviewandroid-imageandroid-bitmap

How to convert string path to Base64 string?


in simple terms: in my onActivityResult() method I upload images into imageviews using the image's path. It's fast and great, but the problem is, I want to convert that string path to a Base64 string. I want to display the image as a Base64 string and send the Base64 string to my database so it can be used in the IOS version of our app. Below is what I currently have, and I have tried bitmaps and stuff but I keep getting a out of memory error! I hope you guys can give me insight on how I can image path's and convert them into base64 strings and upload those into imageviews without out of memory errors.

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        addImageImageView.setVisibility(View.GONE);
        if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            //First we gotta make sure to add the images to
            ArrayList<Image> imagesFromGallery = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);//Image is a personal object I made.

            for (int i = 0; i < imagesFromGallery.size(); i++) {
                images.add(imagesFromGallery.get(i).path);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(20, 20, 0, 0);//5dp = 20 pixels
                lp.height = 720;//180dp = 720pixels
                lp.width = 1400;//330dp = 1320 pixels.
                ImageView newImageView = new ImageView(this);
                newImageView.setLayoutParams(lp);
                Glide.with(this).load(imagesFromGallery.get(i)).centerCrop().into(newImageView);
                imageLinearLayout.addView(newImageView, 0);
            }
    }

Solution

  • Sending side(Encoding)

    byte[] data = imagePath.getBytes("UTF-8");
    String base64 = Base64.encodeToString(data, Base64.DEFAULT);
    

    Receiving side(Decoding)

    byte[] data = Base64.decode(base64, Base64.DEFAULT);
    String imagePath = new String(data, "UTF-8");