Android使用 BASE64Encoder实现图片的Base64编码转换(可用来存储到数据库中)学习笔记(一)
关于
将图片保存为base64码的好处就是可以存储到数据库中,有人说图片的路径不也可以吗,但是这样当本地图片删掉就没了,而且图片转64编码的实现方法也很简单。
效果图
实现第一步,修改activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@color/colorPrimaryDark">
<LinearLayout
android:id="@+id/layout_back"
android:layout_width="40dp"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
//这里的都可以注释掉,与本篇无关
android:background="@drawable/back" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="2dp"
android:gravity="center"
android:orientation="horizontal">
</LinearLayout>
</android.support.v7.widget.Toolbar>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_weight="1"
android:orientation="vertical">
<ImageView
android:id="@+id/image_base64"
android:layout_width="150dp"
android:layout_height="150dp"
/>
<EditText
android:id="@+id/edit_base664"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:id="@+id/btn_photo"
style="?android:attr/borderlessButtonStyle"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="25dp"
//自己设置颜色
android:background="@drawable/normal_btn_pushstyle"
android:text="拍照"
android:textColor="#fff"
android:textSize="16sp" />
</LinearLayout>
第二步,修改BASE64Encoder.java
package com.example.imagebase64;
import java.io.IOException;
import java.io.OutputStream;
public class BASE64Encoder extends CharacterEncoder {
protected int bytesPerAtom() {
return 3;
}
protected int bytesPerLine() {
return 57;
}
private static final char[] pem_array =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a',
'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x'