package com.wangyunjie.test.base64;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class ImageToBase64 {
public static void main(String[] args) {
try {
String str = getImgFromUrl("G:/testFile/test-compress.png");
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getImgFromUrl(String imgUrl) throws Exception {
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
File file = new File(imgUrl);
try {
is = new FileInputStream(file);
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
return Base64Util.encode(outStream.toByteArray());
} catch (Exception e) {
throw new Exception(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
}
}
}
}
}
package com.wangyunjie.test.base64;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.stream.FileImageInputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Util {
public static byte[] decode(String base64Str) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(replaceEnter(base64Str));
}
public static String encode(byte[] image) {
BASE64Encoder decoder = new BASE64Encoder();
return replaceEnter(decoder.encode(image));
}
public static String encode(String uri) {
BASE64Encoder encoder = new BASE64Encoder();
return replaceEnter(encoder.encode(uri.getBytes()));
}
public static byte[] imageTobyte(String path) {
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
public static String replaceEnter(String str) {
String reg = "[\n-\r]";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
return m.replaceAll("");
}
}