如何将字符串路径转换为Base64字符串?

时间:2016-10-28 23:13:31

标签: android base64 android-imageview android-image android-bitmap

简单来说:在我的onActivityResult()方法中,我使用图像的路径将图像上传到ima​​geviews中。它快速而且很棒,但问题是,我想将该字符串路径转换为Base64字符串。我想将图像显示为Base64字符串并将Base64字符串发送到我的数据库,以便它可以在我们的应用程序的IOS版本中使用。下面是我目前所拥有的,我已经尝试过位图和东西,但我不断出现内存错误!我希望你们能够让我了解如何对路径进行映像并将它们转换为base64字符串并将其上传到ima​​geview而不会出现内存错误。

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

1 个答案:

答案 0 :(得分:4)

发送方(编码)

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

接收方(解码)

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