Java implementation BASE64 Mutual codec transform picture and string __java

Source: Internet
Author: User
Tags base64
Base64 Basic Algorithm principle


String instance (Base64 codec for S13)
Test: S13
Code: Czez
Decoding: S13



How to encode the process analysis of S13 for Czez:



BASE64 requires converting every three 8Bit bytes to four 6Bit bytes (3*8 = 4*6 = 24), and then adding 6Bit two-bit high 0 to form four 8Bit bytes, that is, the converted string is theoretically going to be 1/3 longer than the original.
The process of 3*8 to 4*6 between S13 binary systems
115 49 51
01110011 00110001 00110011 (ASC to binary)
011100 110011 000100 110011 (divided into 4 groups)
00011100 00110011 00000100 00110011 (full 8-digit group)
28 51 4 51 (obtained after the encoded ASC)
Czez (corresponding string)
——— Baidu Encyclopedia



Here are three ways to do this:
1 Use Commons-codec.jar Package
Download Address http://commons.apache.org/proper/commons-codec/download_codec.cgi
Commons a toolkit for handling commonly used coding methods in a project, such as DES, SHA1, MD5, BASE64,URL,SOUNDX, etc.
Not only is it encoded, it can also be used for decoding.
2 Using Sun.misc.BASE64Encoder
The JDK contains base64encoder that can be used directly, but because it is not part of the JDK's standard library category, Eclipse is not directly accessible and requires related configuration;
3 Direct coding of base64 conversion logic
Use base64 to convert byte conversions Commons-codec.jar base64


Need to download application Commons-codec.jar package
package commonscodec.demo.base64;

Import java.io.UnsupportedEncodingException;
Import org.apache.commons.codec.binary.Base64;

public class Main {public
    static void Main (string[] args) {

        String str = "S13";
        Base64 base64 = new Base64 ();
        try {
            str = base64.encodetostring (str.getbytes ("UTF-8"));
        } catch (Unsupportedencodingexception e) {
            E.printstacktrace ();
        }
        SYSTEM.OUT.PRINTLN ("BASE64 encoded:" + str);
    }
Sun.misc.BASE64Encoder for base64 conversion
//If the sun.misc.base64decoder package cannot be found, you need to configure it
package sunmisc.demo.base64;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/ / /
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Main {
public static void main(String[] args) {
String strImg = GetImageStr();
System.out.println(strImg);
GenerateImage(strImg);
}
//Convert image to Base64 string
public static String GetImageStr() {
//Convert the picture file to byte array string and encode it with Base64
String imgFile = "d://test.png";
InputStream in = null;
byte[] data = null;
//Read image byte array
Try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
In.close ();
} catch (IOException e) {
e.printStackTrace();
}
//Encoding byte array Base64
BASE64Encoder encoder = new BASE64Encoder();
//Returns Base64 encoded byte array string
return encoder.encode(data);
}
//Base64 string to image
public static boolean GenerateImage(String imgStr) {
//Decode byte array string Base64 and generate picture
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
Try {
//Base64 decoding
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
If (B [i] < 0) {/ / adjust exception data
B[i] + = 256;
}
}
//Generate a new picture
String imgFilePath = "d://222.png";
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
Out.flush ();
Out.close ();
Return true;
} catch (Exception e) {
return false;
}
}
}


If the Sun.misc.BASE64Decoder package is not found, you need to configure the following
Right key item-Properties-Java bulid path-JRE System library-Access rules- Resolution Select accessible Fill in * *, click OK complete configuration
write logic directly to Base64 conversion


//From http://blog.csdn.net/lastsweetop/article/details/5314640
package com.test.base64;
public class Main {
* *
*Encode the original data as Base64
* /
static public char[] encode(byte[] data) {
char[] out = new char[((data.length + 2) / 3) * 4];
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
boolean quad = false;
boolean trip = false;
int val = (0xFF &amp; (int) data[i]);
Val = 8;
if ((i + 1) < data.length) {
val |= (0xFF &amp; (int) data[i + 1]);
Trip = true;
}
Val = 8;
if ((i + 2) < data.length) {
val |= (0xFF &amp; (int) data[i + 2]);
Quad = true;
}
out[index + 3] = alphabet[(quad ? (val &amp; 0x3F) : 64)];
Val = 6;
out[index + 2] = alphabet[(trip ? (val &amp; 0x3F) : 64)];
Val = 6;
out[index + 1] = alphabet[val &amp; 0x3F];
Val = 6;
out[index + 0] = alphabet[val &amp; 0x3F];
}
Return out;
}
* *
*Decoding Base64 encoded data into raw data
* /
static public byte[] decode(char[] data) {
int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 &amp;&amp; data[data.length - 1] == '=')
--len;
if (data.length > 1 &amp;&amp; data[data.length - 2] == '=')
--len;
byte[] out = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix = 0; ix < data.length; ix++) {
int value = codes[data[ix] &amp; 0xFF];
if (value >= 0) {
Accum = 6;
Shift + = 6;
accum |= value;
if (shift >= 8) {
Shift = 8;
out[index++] = (byte) ((accum >> shift) &amp; 0xff);
}
}
}
if (index != out.length)
throw new Error("miscalculated data length!");
Return out;
}
static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray();
static private byte[] codes = new byte[256];
Static {
for (int i = 0; i < 256; i++)
codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
codes[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
codes[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}
public static void main(String[] args) throws Exception {
//Encrypt to Base64
String strSrc = "s13";
String strOut = new String(Main.encode(strSrc.getBytes("GB18030")));
System. Out. Println ("test: S13");
System. Out. Println ("Code:" + Strout);
String strOut2 = new String(Main.decode(strOut.toCharArray()),
"GB18030");
System. Out. Println ("decode:" + strout2);
}
} 


Test code from Network
Three test source Download HTTP://PAN.BAIDU.COM/S/1KVFIES3
Test results


Test: S13
Encoding: Czez
decoding: S13
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.