解析 Base64 编码字符串表示的图片为二进制数据,根据上面的算法反过来解析即可。
1 2
|
compile 'commons-codec:commons-codec:1.10' compile 'commons-io:commons-io:2.5'
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils;
import java.io.File; import java.io.IOException;
public class ImageBase64Utils { public static void main(String[] argv) throws Exception { String str = imageToBase64String("/Users/Biao/Pictures/ade.jpg"); System.out.println(str);
saveBase64ImageStringToImage("/Users/Biao/Desktop", "y", str); }
public static String imageToBase64String(String imagePath) throws IOException { String prefix = String.format("data:image/%s;base64,", FilenameUtils.getExtension(imagePath).toLowerCase()); byte[] content = FileUtils.readFileToByteArray(new File(imagePath));
return prefix + Base64.encodeBase64String(content); }
public static void saveBase64ImageStringToImage(String directory, String baseName, String base64ImageString) throws IOException { int commaIndex = base64ImageString.indexOf(","); String extension = base64ImageString.substring(0, commaIndex).replaceAll("data:image/(.+);base64", "$1"); byte[] content = Base64.decodeBase64(base64ImageString.substring(commaIndex));
FileUtils.writeByteArrayToFile(new File(directory, baseName +"."+extension), content); } }
|