欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Java Base64位编码与String字符串的相互转换,Base64与Bitmap的相互转换实例代码

程序员文章站 2023-11-30 17:37:46
首先是网上大神给的类 package com.duanlian.daimengmusic.utils; public final class base64uti...

首先是网上大神给的类

package com.duanlian.daimengmusic.utils;
public final class base64util {
  private static final int baselength = 128;
  private static final int lookuplength = 64;
  private static final int twentyfourbitgroup = 24;
  private static final int eightbit = 8;
  private static final int sixteenbit = 16;
  private static final int fourbyte = 4;
  private static final int sign = -128;
  private static char pad = '=';
  private static byte[] base64alphabet = new byte[baselength];
  private static char[] lookupbase64alphabet = new char[lookuplength];
  static {
    for (int i = 0; i < baselength; ++i) {
      base64alphabet[i] = -1;
    }
    for (int i = 'z'; i >= 'a'; i--) {
      base64alphabet[i] = (byte) (i - 'a');
    }
    for (int i = 'z'; i >= 'a'; i--) {
      base64alphabet[i] = (byte) (i - 'a' + 26);
    }
    for (int i = '9'; i >= '0'; i--) {
      base64alphabet[i] = (byte) (i - '0' + 52);
    }
    base64alphabet['+'] = 62;
    base64alphabet['/'] = 63;
    for (int i = 0; i <= 25; i++) {
      lookupbase64alphabet[i] = (char) ('a' + i);
    }
    for (int i = 26, j = 0; i <= 51; i++, j++) {
      lookupbase64alphabet[i] = (char) ('a' + j);
    }
    for (int i = 52, j = 0; i <= 61; i++, j++) {
      lookupbase64alphabet[i] = (char) ('0' + j);
    }
    lookupbase64alphabet[62] = (char) '+';
    lookupbase64alphabet[63] = (char) '/';
  }
  private static boolean iswhitespace(char octect) {
    return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
  }
  private static boolean ispad(char octect) {
    return (octect == pad);
  }
  private static boolean isdata(char octect) {
    return (octect < baselength && base64alphabet[octect] != -1);
  }
  /**
   把64位byte数组转换成string
   */
  public static string encode(byte[] binarydata) {
    if (binarydata == null) {
      return null;
    }
    int lengthdatabits = binarydata.length * eightbit;
    if (lengthdatabits == 0) {
      return "";
    }
    int fewerthan24bits = lengthdatabits % twentyfourbitgroup;
    int numbertriplets = lengthdatabits / twentyfourbitgroup;
    int numberquartet = fewerthan24bits != 0 ? numbertriplets + 1
        : numbertriplets;
    char encodeddata[] = null;
    encodeddata = new char[numberquartet * 4];
    byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
    int encodedindex = 0;
    int dataindex = 0;
    for (int i = 0; i < numbertriplets; i++) {
      b1 = binarydata[dataindex++];
      b2 = binarydata[dataindex++];
      b3 = binarydata[dataindex++];
      l = (byte) (b2 & 0x0f);
      k = (byte) (b1 & 0x03);
      byte val1 = ((b1 & sign) == 0) ? (byte) (b1 >> 2)
          : (byte) ((b1) >> 2 ^ 0xc0);
      byte val2 = ((b2 & sign) == 0) ? (byte) (b2 >> 4)
          : (byte) ((b2) >> 4 ^ 0xf0);
      byte val3 = ((b3 & sign) == 0) ? (byte) (b3 >> 6)
          : (byte) ((b3) >> 6 ^ 0xfc);
      encodeddata[encodedindex++] = lookupbase64alphabet[val1];
      encodeddata[encodedindex++] = lookupbase64alphabet[val2 | (k << 4)];
      encodeddata[encodedindex++] = lookupbase64alphabet[(l << 2) | val3];
      encodeddata[encodedindex++] = lookupbase64alphabet[b3 & 0x3f];
    }
    // form integral number of 6-bit groups
    if (fewerthan24bits == eightbit) {
      b1 = binarydata[dataindex];
      k = (byte) (b1 & 0x03);
      byte val1 = ((b1 & sign) == 0) ? (byte) (b1 >> 2)
          : (byte) ((b1) >> 2 ^ 0xc0);
      encodeddata[encodedindex++] = lookupbase64alphabet[val1];
      encodeddata[encodedindex++] = lookupbase64alphabet[k << 4];
      encodeddata[encodedindex++] = pad;
      encodeddata[encodedindex++] = pad;
    } else if (fewerthan24bits == sixteenbit) {
      b1 = binarydata[dataindex];
      b2 = binarydata[dataindex + 1];
      l = (byte) (b2 & 0x0f);
      k = (byte) (b1 & 0x03);
      byte val1 = ((b1 & sign) == 0) ? (byte) (b1 >> 2)
          : (byte) ((b1) >> 2 ^ 0xc0);
      byte val2 = ((b2 & sign) == 0) ? (byte) (b2 >> 4)
          : (byte) ((b2) >> 4 ^ 0xf0);
      encodeddata[encodedindex++] = lookupbase64alphabet[val1];
      encodeddata[encodedindex++] = lookupbase64alphabet[val2 | (k << 4)];
      encodeddata[encodedindex++] = lookupbase64alphabet[l << 2];
      encodeddata[encodedindex++] = pad;
    }
    return new string(encodeddata);
  }
  /**
   * 把base64位编码转换成byte数组
   */
  public static byte[] decode(string encoded) {
    if (encoded == null) {
      return null;
    }
    char[] base64data = encoded.tochararray();
    // remove white spaces
    int len = removewhitespace(base64data);
    if (len % fourbyte != 0) {
      return null;// should be divisible by four
    }
    int numberquadruple = (len / fourbyte);
    if (numberquadruple == 0) {
      return new byte[0];
    }
    byte decodeddata[] = null;
    byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
    char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
    int i = 0;
    int encodedindex = 0;
    int dataindex = 0;
    decodeddata = new byte[(numberquadruple) * 3];
    for (; i < numberquadruple - 1; i++) {
      if (!isdata((d1 = base64data[dataindex++]))
          || !isdata((d2 = base64data[dataindex++]))
          || !isdata((d3 = base64data[dataindex++]))
          || !isdata((d4 = base64data[dataindex++]))) {
        return null;
      }// if found "no data" just return null
      b1 = base64alphabet[d1];
      b2 = base64alphabet[d2];
      b3 = base64alphabet[d3];
      b4 = base64alphabet[d4];
      decodeddata[encodedindex++] = (byte) (b1 << 2 | b2 >> 4);
      decodeddata[encodedindex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
      decodeddata[encodedindex++] = (byte) (b3 << 6 | b4);
    }
    if (!isdata((d1 = base64data[dataindex++]))
        || !isdata((d2 = base64data[dataindex++]))) {
      return null;// if found "no data" just return null
    }
    b1 = base64alphabet[d1];
    b2 = base64alphabet[d2];
    d3 = base64data[dataindex++];
    d4 = base64data[dataindex++];
    if (!isdata((d3)) || !isdata((d4))) {// check if they are pad characters
      if (ispad(d3) && ispad(d4)) {
        if ((b2 & 0xf) != 0)// last 4 bits should be zero
        {
          return null;
        }
        byte[] tmp = new byte[i * 3 + 1];
        system.arraycopy(decodeddata, 0, tmp, 0, i * 3);
        tmp[encodedindex] = (byte) (b1 << 2 | b2 >> 4);
        return tmp;
      } else if (!ispad(d3) && ispad(d4)) {
        b3 = base64alphabet[d3];
        if ((b3 & 0x3) != 0)// last 2 bits should be zero
        {
          return null;
        }
        byte[] tmp = new byte[i * 3 + 2];
        system.arraycopy(decodeddata, 0, tmp, 0, i * 3);
        tmp[encodedindex++] = (byte) (b1 << 2 | b2 >> 4);
        tmp[encodedindex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
        return tmp;
      } else {
        return null;
      }
    } else { // no pad e.g 3cql
      b3 = base64alphabet[d3];
      b4 = base64alphabet[d4];
      decodeddata[encodedindex++] = (byte) (b1 << 2 | b2 >> 4);
      decodeddata[encodedindex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
      decodeddata[encodedindex++] = (byte) (b3 << 6 | b4);
    }
    return decodeddata;
  }
  /**
   * remove whitespace from mime containing encoded base64util data.
   * 
   * @param data
   *      the byte array of base64 data (with ws)
   * @return the new length
   */
  private static int removewhitespace(char[] data) {
    if (data == null) {
      return 0;
    }
    // count characters that's not whitespace
    int newsize = 0;
    int len = data.length;
    for (int i = 0; i < len; i++) {
      if (!iswhitespace(data[i])) {
        data[newsize++] = data[i];
      }
    }
    return newsize;
  }
}

然后是我经过2次封装的类,注释很清楚,拿过去直接用就行

package com.duanlian.daimengmusic.utils;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.util.base64;
import java.io.bytearrayoutputstream;
import java.io.ioexception;
/**
 * 转换编码
 */
public class base64object {
  /**
   * 把base64的string码转换成正常显示的字符串
   */
  public static string base64tostring(string base64) {
    byte[] decode = base64util.decode(base64);
    string s = new string(decode);
    return s;
  }
  /**
   * 把string的转换成base64码
   */
  public static string stringtobase64(string ss) {
    byte[] bytes = ss.getbytes();
    string encode = base64util.encode(bytes);
    return encode;
  }
  /**
   * bitmap转为base64
   * @param bitmap
   * @return
   */
  public static string bitmaptobase641(bitmap bitmap) {
    string result = null;
    bytearrayoutputstream baos = null;
    try {
      if (bitmap != null) {
        baos = new bytearrayoutputstream();
        bitmap.compress(bitmap.compressformat.jpeg, 100, baos);
        baos.flush();
        baos.close();
        byte[] bitmapbytes = baos.tobytearray();
        result = base64.encodetostring(bitmapbytes, base64.default);
      }
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      try {
        if (baos != null) {
          baos.flush();
          baos.close();
        }
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
    return result;
  }
  /**
   * base64转为bitmap
   * @param base64data
   * @return
   */
  public static bitmap base64tobitmap(string base64data) {
    byte[] bytes = base64.decode(base64data, base64.default);
    return bitmapfactory.decodebytearray(bytes, 0, bytes.length);
  }
}

以上所述是小编给大家介绍的java base64位编码与string字符串的相互转换,base64与bitmap的相互转换实例代码,希望对大家有所帮助