本贴讲的是 java 图片转base64 字符串不换行,同时不换行的字符串 转图片
主要的方法是用到了java的 import org.apache.commons.codec.binary.Base64
例:
String str = "sakjdklsajdlas思考的萨克达离开时间的扩散";
byte[] ets = Base64.encodeBase64(str.getBytes());
System.out.println(new String(ets));
byte[] dts = Base64.decodeBase64(ets);
System.out.println(new String(dts));
直接贴代码
package base64;
import java.io.File;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
/**
* 图片转化为base64
* base64转化为图片
* 不换行的转换
* 两个方法分别是:1.图片转化为base64,同时写入 txt文件。2. txt文件读取转化为 图片
* 用到了 org.apache.commons.codec.binary.Base64 和 org.apache.commons.io.FileUtils
*
*/
public class test1 {
public static void main(String[] args) {
writeByBase64();
}
// 图片转化为base64
public static void readToBase64() {
String path = "C:\\Users\\makaka\\Desktop\\aa\\pa.jpg";
byte[] byt = null;
File file = new File(path);
try {
byt = FileUtils.readFileToByteArray(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encodedBytes = Base64.encodeBase64(byt);
// String str = new String(encodedBytes);
// System.out.println(new String(encodedBytes));
String filePath = "C:\\Users\\makaka\\Desktop\\aa\\2333.txt";
File filetxt = new File(filePath);
try {
FileUtils.writeByteArrayToFile(filetxt, encodedBytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// base64 转换为图片
public static void writeByBase64() {
String path = "C:\\Users\\makaka\\Desktop\\aa\\2_base64.txt";
File file = new File(path);
byte[] readFileToByteArray =null;
try {
readFileToByteArray = FileUtils.readFileToByteArray(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pathImage = "C:\\Users\\makaka\\Desktop\\aa\\2.jpg";
File fileImage = new File(pathImage);
byte[] decodedBytes = Base64.decodeBase64(readFileToByteArray);
try {
FileUtils.writeByteArrayToFile(fileImage, decodedBytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果有什么错误请指正,谢谢!