Android实现将Base64Encoder编码转为图片学习笔记(二)
关于
关于将图片转换为base64编码的方法,请参考文章Android使用 BASE64Encoder实现图片的Base64编码转换(可用来存储到数据库中)学习笔记(一)本文直接在上一篇基础上修改。
效果
实现第一步,修改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"
tools:context=".MainActivity"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@color/colorPrimaryDark">
</android.support.v7.widget.Toolbar>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
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:text="拍照"
android:textSize="16sp" />
<Button
android:id="@+id/btn_jiema"
android:text="解码"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/ima_jiema"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
第二步,修改CharacterEncoder.java
package com.example.a13115.blog;
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);
}
}
第三步,修改BASE64Encoder.java
package com.example.a13115.blog;
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)]);
}
}
}
第四步,修改MainActivity.java
package com.example.a13115.blog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
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;
@BindView(R.id.btn_jiema)
Button btn_jie;
@BindView(R.id.ima_jiema)
ImageView image_jie;
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);
btn_jie.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_photo:
startCamera(100);
break;
case R.id.btn_jiema:
image_jie.setImageBitmap(MainActivity.stringToBitmap(photo_base64));
break;
}
}
//将64编码转为Bitmap
private static Bitmap stringToBitmap(String photo_base64) {
Bitmap bitmap = null;
byte[] bitmapArry = Base64.decode(photo_base64,Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArry,0,bitmapArry.length);
return bitmap;
}
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);
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
好啦,本篇就到此结束啦,关于图片的base64转换就算完成了,有问题欢迎留言,欢迎批评指正!
后续追加 法二
使用glide框架加载(4.11版本亲测可用)