如何在 Android 中将图像转换为 base64 字符串?


本例演示了如何在 Android 中执行I操作。

步骤 1 − 在 Android Studio 中创建一个新项目,转到 File ⇒ New Project,然后填写所有必需的详细信息以创建一个新项目。

步骤 2 − 将以下代码添加到 res/layout/activity_main.xml 中。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".MainActivity">
<TextView
   android:id="@+id/textView"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_centerInParent="true"
   android:textSize="12sp"
   android:textStyle="bold" />
</RelativeLayout>

步骤 3 − 将以下代码添加到 src/MainActivity.java 中

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @SuppressLint("WrongThread")
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.instaimage);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
      byte[] imageBytes = byteArrayOutputStream.toByteArray();
      String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
      textView.setText(imageString);
   }
}

步骤 4 − 将以下代码添加到 androidManifest.xml 中。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

我们来试运行您的应用程序。我假设您已将您的真机 Android 移动设备连接到了您的计算机。要从 Android Studio 中运行应用程序,请打开您的某个项目活动文件,然后单击工具栏中的运行Play Icon 图标。选择您的移动设备作为一个选项,然后查看您的移动设备,它会显示您的默认屏幕 −

更新于:2020 年 7 月 7 日

2K+ 次浏览

开始你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.