一般图片base64开头都是data:image/png;base64,或者data:image/jpeg;base64,
解码只需后面开始的数据。代码如下
base64=base64.substring(23);//或者22,截掉前缀
//开始解码
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(base64);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//压缩
private static byte[] compressPic(byte[] imageByte, int width, int height, boolean gp) {
byte[] inByte = null;
try {
ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
Image img = ImageIO.read(byteInput);
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
return inByte;
} else {
int newWidth; int newHeight;
// 判断是否是等比缩放
if (gp == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null)) / (double) width + 0.1;
double rate2 = ((double) img.getHeight(null)) / (double) height + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = width; // 输出的图片宽度
newHeight = height; // 输出的图片高度
}
BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
/*
* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的
* 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
ImageWriter imgWrier;
ImageWriteParam imgWriteParams;
// 指定写图片的方式为 jpg
imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
//将压缩后的图片返回字节流
ByteArrayOutputStream out = new ByteArrayOutputStream(imageByte.length);
imgWrier.reset();
// 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
// 调用write方法,就可以向输入流写图片
imgWrier.write(null, new IIOImage(tag, null, null), imgWriteParams);
out.flush();
out.close();
byteInput.close();
inByte = out.toByteArray();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return inByte;
}
//图片链接转base64
public static String GetUrlImageToBase64(String url) throws Exception {
if (url == null || "".equals(url.trim()))
return null;
URL u = new URL(url);
// 打开图片路径
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
// 设置请求方式为GET
conn.setRequestMethod("GET");
// 设置超时响应时间为5秒
conn.setConnectTimeout(5000);
// 通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
// 读取图片字节数组
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
byte[] data=outStream.toByteArray();
// byte[] data = new byte[inStream.available()];
inStream.read(data);
inStream.close();
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(data);
}