Android使用 BASE64Encoder实现图片的Base64编码转换(可用来存储到数据库中)学习笔记(一)

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', 'y', 'z', '0',
                    '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '='};

    protected void encodeAtom(OutputStream paramOutputStream,
                              byte[] paramArrayOfByte, int paramInt1, int paramInt2)
            throws IOException {
        int i;
        int j;
        int k;
        if (paramInt2 == 1) {
            i = paramArrayOfByte[paramInt1];
            j = 0;
            k = 0;
            paramOutputStream.write(pem_array[(i >>> 2 & 0x3F)]);
            paramOutputStream
                    .write(pem_array[((i << 4 & 0x30) + (j >>> 4 & 0xF))]);
            paramOutputStream.write(61);
            paramOutputStream.write(61);
        } else if (paramInt2 == 2) {
            i = paramArrayOfByte[paramInt1];
            j = paramArrayOfByte[(paramInt1 + 1)];
            k = 0;
            paramOutputStream.write(pem_array[(i >>> 2 & 0x3F)]);
            paramOutputStream
                    .write(pem_array[((i << 4 & 0x30) + (j >>> 4 & 0xF))]);
            paramOutputStream
                    .write(pem_array[((j << 2 & 0x3C) + (k >>> 6 & 0x3))]);
            paramOutputStream.write(61);
        } else {
            i = paramArrayOfByte[paramInt1];
            j = paramArrayOfByte[(paramInt1 + 1)];
            k = paramArrayOfByte[(paramInt1 + 2)];
            paramOutputStream.write(pem_array[(i >>> 2 & 0x3F)]);
            paramOutputStream
                    .write(pem_array[((i << 4 & 0x30) + (j >>> 4 & 0xF))]);
            paramOutputStream
                    .write(pem_array[((j << 2 & 0x3C) + (k >>> 6 & 0x3))]);
            paramOutputStream.write(pem_array[(k & 0x3F)]);
        }
    }
}

第三步,修改CharacterEncoder.java

package com.example.imagebase64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;

public abstract class CharacterEncoder {
    protected PrintStream pStream;

    protected abstract int bytesPerAtom();

    protected abstract int bytesPerLine();

    protected void encodeBufferPrefix(OutputStream paramOutputStream)
            throws IOException {
        this.pStream = new PrintStream(paramOutputStream);
    }

    protected void encodeBufferSuffix(OutputStream paramOutputStream)
            throws IOException {
    }

    protected void encodeLinePrefix(OutputStream paramOutputStream, int paramInt)
            throws IOException {
    }

    protected void encodeLineSuffix(OutputStream paramOutputStream)
            throws IOException {
        this.pStream.println();
    }

    protected abstract void encodeAtom(OutputStream paramOutputStream, byte[] paramArrayOfByte, int paramInt1, int paramInt2)
            throws IOException;

    protected int readFully(InputStream paramInputStream, byte[] paramArrayOfByte)
            throws IOException {
        for (int i = 0; i < paramArrayOfByte.length; i++) {
            int j = paramInputStream.read();
            if (j == -1) {
                return i;
            }
            paramArrayOfByte[i] = ((byte) j);
        }
        return paramArrayOfByte.length;
    }

    public void encode(InputStream paramInputStream, OutputStream paramOutputStream)
            throws IOException {
        byte[] arrayOfByte = new byte[bytesPerLine()];

        encodeBufferPrefix(paramOutputStream);
        for (; ; ) {
            int j = readFully(paramInputStream, arrayOfByte);
            if (j == 0) {
                break;
            }
            encodeLinePrefix(paramOutputStream, j);
            for (int i = 0; i < j; i += bytesPerAtom()) {
                if (i + bytesPerAtom() <= j) {
                    encodeAtom(paramOutputStream, arrayOfByte, i, bytesPerAtom());
                } else {
                    encodeAtom(paramOutputStream, arrayOfByte, i, j - i);
                }
            }
            if (j < bytesPerLine()) {
                break;
            }
            encodeLineSuffix(paramOutputStream);
        }
        encodeBufferSuffix(paramOutputStream);
    }

    public void encode(byte[] paramArrayOfByte, OutputStream paramOutputStream)
            throws IOException {
        ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(paramArrayOfByte);
        encode(localByteArrayInputStream, paramOutputStream);
    }

    public String encode(byte[] paramArrayOfByte) {
        ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(paramArrayOfByte);
        String str = null;
        try {
            encode(localByteArrayInputStream, localByteArrayOutputStream);

            str = localByteArrayOutputStream.toString("8859_1");
        } catch (Exception localException) {
            throw new Error("CharacterEncoder.encode internal error");
        }
        return str;
    }

    private byte[] getBytes(ByteBuffer paramByteBuffer) {
        byte[] localObject = null;
        if (paramByteBuffer.hasArray()) {
            byte[] arrayOfByte = paramByteBuffer.array();
            if ((arrayOfByte.length == paramByteBuffer.capacity()) && (arrayOfByte.length == paramByteBuffer.remaining())) {
                localObject = arrayOfByte;
                paramByteBuffer.position(paramByteBuffer.limit());
            }
        }
        if (localObject == null) {
            localObject = new byte[paramByteBuffer.remaining()];


            paramByteBuffer.get(localObject);
        }
        return localObject;
    }

    public void encode(ByteBuffer paramByteBuffer, OutputStream paramOutputStream)
            throws IOException {
        byte[] arrayOfByte = getBytes(paramByteBuffer);
        encode(arrayOfByte, paramOutputStream);
    }

    public String encode(ByteBuffer paramByteBuffer) {
        byte[] arrayOfByte = getBytes(paramByteBuffer);
        return encode(arrayOfByte);
    }

    public void encodeBuffer(InputStream paramInputStream, OutputStream paramOutputStream)
            throws IOException {
        byte[] arrayOfByte = new byte[bytesPerLine()];

        encodeBufferPrefix(paramOutputStream);
        for (; ; ) {
            int j = readFully(paramInputStream, arrayOfByte);
            if (j != 0) {
                encodeLinePrefix(paramOutputStream, j);
                for (int i = 0; i < j; i += bytesPerAtom()) {
                    if (i + bytesPerAtom() <= j) {
                        encodeAtom(paramOutputStream, arrayOfByte, i, bytesPerAtom());
                    } else {
                        encodeAtom(paramOutputStream, arrayOfByte, i, j - i);
                    }
                }
                encodeLineSuffix(paramOutputStream);
                if (j < bytesPerLine()) {
                    break;
                }
            }
        }
        encodeBufferSuffix(paramOutputStream);
    }

    public void encodeBuffer(byte[] paramArrayOfByte, OutputStream paramOutputStream)
            throws IOException {
        ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(paramArrayOfByte);
        encodeBuffer(localByteArrayInputStream, paramOutputStream);
    }

    public String encodeBuffer(byte[] paramArrayOfByte) {
        ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(paramArrayOfByte);
        try {
            encodeBuffer(localByteArrayInputStream, localByteArrayOutputStream);
        } catch (Exception localException) {
            throw new Error("CharacterEncoder.encodeBuffer internal error");
        }
        return localByteArrayOutputStream.toString();
    }

    public void encodeBuffer(ByteBuffer paramByteBuffer, OutputStream paramOutputStream)
            throws IOException {
        byte[] arrayOfByte = getBytes(paramByteBuffer);
        encodeBuffer(arrayOfByte, paramOutputStream);
    }

    public String encodeBuffer(ByteBuffer paramByteBuffer) {
        byte[] arrayOfByte = getBytes(paramByteBuffer);
        return encodeBuffer(arrayOfByte);
    }
}

第四步,修改MainActivity.java

package com.example.imagebase64;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.util.Base64;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //关于Butterknife的使用可以自行百度或是参考我之前的文章,也可以不使用
    @BindView(R.id.image_base64)
    ImageView imageView_base64;
    @BindView(R.id.btn_photo)
    Button button_photo;
    @BindView(R.id.edit_base664)
    EditText editText_baase64;
    Context mContext;
    String photo_base64;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        mContext = MainActivity.this;
        button_photo.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_photo:
                startCamera(100);
                break;
        }
    }

    private void startCamera(int flag) {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
            startActivityForResult(intent, flag);
        } catch (Exception ex) {
            Toast.makeText(mContext, "打开相机失败",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 100:
                if (resultCode == -1){  //result 返回的是-1 表示拍照成功 返回的是 0 表示拍照失败
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    imageView_base64.setImageBitmap(bitmap);
                    bitmapToString(bitmap);
                    //调用静态方法
                    photo_base64 = MainActivity.bitmapToString(bitmap);
                    editText_baase64.setText(photo_base64);
                }
        }
    }

    private static String bitmapToString(Bitmap bitmap) {
        String string = null;
        ByteArrayOutputStream btString = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, btString);
        byte[] bytes = btString.toByteArray();
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }
}

好了,本篇到此结束,有问题欢迎批评指正,后续将会继续研究。
下一篇是将base64的图片的编码转成图片:Android实现将Base64Encoder编码转为图片学习笔记(二)

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雪の星空朝酱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值