如何在 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.