第一更 任务需要将图片byte[]转成一个原图1/4大小的缩略图,并以base64返回。
思路如下:
开始–>读取图片–>转byte[]–>复制byte[]得到一个新InputStream–>新InputStream转BufferdImage–>新BufferdImage设置长宽–>将新BufferdImage使用ImageIO.write输出到ByteArrayOutputStream–>ByteArrayOutputStream转byte[]–>进行base64编码–>完成
读取:
1.读取图片
2.转为byte[]
转化:
1.byte[]数组 转 buffereImage;
2.设置bufferdImage参数;
3.ImgeIO写bufferdImage到ByteArrayOutputStream;
4.将ByteArrayOutputStream转为byte[];
5.将byte[]数组进行加密返回。
//读取图片
byte[] content = null;
File file = new File("D:/a.pdf");
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
bos.write(b, 0, n);
}
in.close();
bos.close();
content = bos.toByteArray();
图片byte[]数组: content
InputStream in = new ByteArrayInputSteam(content,0,content.length);//数组,起始位置,结束位置
BufferdImage bImage = ImageIO.read(in);//将inputSteam读取成bufferdImage
int height = bImage.getHeight()/4;//获取转化后的高度
int width = bImage.getWidth()/4;//获取转化后的宽度
//声明一个新的BufferdImage
BufferedImage newBImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//设置newBImage的参数
newBImage.getGraphics().drawImage(bImage, 0, 0, width, height, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(newBImage, "jpg", out);
byte[] smallContent = out.toByteArray();
//进行base64加密
String data = Base64.encodeToString(smallContent);
return data;