【问题标题】:How to convert a string image path to Base64 string in android?如何在android中将字符串图像路径转换为Base64字符串?
【发布时间】:2016-10-29 02:38:25
【问题描述】:

所以我正在将字符串路径上传到 imageViews,它工作正常,但我的 IOS 应用程序无法使用我的字符串路径,所以我需要切换到 base 64 字符串。如何将我的字符串路径转换为 ​​base 64 图像并将其上传到 imageview 而不会出现内存不足错误?

以下是我目前在 myActivityResult() 上的内容。

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

【问题讨论】:

  • 参考这个link

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


【解决方案1】:

您可以使用 Base64 Android 类:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

您必须先将图像转换为字节数组。这是一个例子:

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();

所以 byteArrayImage 是 b。

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);

【讨论】:

  • 那么什么是byteArrayImage?
  • 我已经编辑了我的答案。如果有用,别忘了标记为正确答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
相关资源
最近更新 更多