一. 思路
1. 首先是对返回图片的图片 后端进行权限校验 ,如果需要打码的人,则对图片进行打马赛克。不需要的则直接吧图片进行转成base64给进行加码传给前端。需要对图片进行打码的则直接对图片进行打码,再base64加密。
二.代码实现逻辑
- 首先对网络上的图片转成字节流
/**
* 根据地址获得数据的字节流
*
* @param strUrl 网络连接地址
* @return
*/
public static byte[] getImageFromNetByUrl(String strUrl) {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
- 从输入流中获取数据并转成byte数组
/**
* 从输入流中获取数据
*
* @param inStream 输入流
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
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();
return outStream.toByteArray();
}
- 把转成byte数组的图片信息进行打马赛克
public static byte[] ImgMosaic(byte[] btImg) {
byte[] imageInByte = null;
try {
ByteArrayInputStream in = new ByteArrayInputStream(btImg); //将b作为输入流;
BufferedImage img = ImageIO.read(in); //将in作为输入流,读取图片存入image中,而这里in可以为
int size = 5; //马赛克大小
int width = img.getWidth(null); //原图片宽
int height = img.getHeight(null); //原图片高
BufferedImage mosaic = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int xcount = 0; //x方向绘制个数
int ycount = 0; //y方向绘制个数
if (width % size == 0) {
xcount = width / size;
} else {
xcount = width / size + 1;
}
if (height % size == 0) {
ycount = height / size;
} else {
ycount = height / size + 1;
}
int x = 0; //x坐标
int y = 0; //y坐标
//绘制马赛克(绘制矩形并填充颜色)
Graphics2D g = mosaic.createGraphics();
for (int i = 0; i < xcount; i++) {
for (int j = 0; j < ycount; j++) {
//马赛克矩形格大小
int mwidth = size;
int mheight = size;
if (i == xcount - 1) { //横向最后一个不够一个size
mwidth = width - x;
}
if (j == ycount - 1) { //纵向最后一个不够一个size
mheight = height - y;
}
//矩形颜色取中心像素点RGB值
int centerX = x;
int centerY = y;
if (mwidth % 2 == 0) {
centerX += mwidth / 2;
} else {
centerX += (mwidth - 1) / 2;
}
if (mheight % 2 == 0) {
centerY += mheight / 2;
} else {
centerY += (mheight - 1) / 2;
}
Color color = new Color(img.getRGB(centerX, centerY));
g.setColor(color);
g.fillRect(x, y, mwidth, mheight);
y = y + size;// 计算下一个矩形的y坐标
}
y = 0;// 还原y坐标
x = x + size;// 计算x坐标
}
//马赛克处理结束
g.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(mosaic, "jpg", baos);
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageInByte;
}
4.多图片转成buse64
/**
* 将图片的byte字节转成base64字符串
* @param imageInByte
* @return
*/
public static String GetImageStr(byte[] imageInByte){
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
String encode = encoder.encode(imageInByte);//返回Base64编码过的字节数组字符串
return encode;
}