java生成pdf缩略图

本文介绍了如何在Java中将图片转换为1/4大小的缩略图,并以base64编码形式返回。流程包括从byte[]读取图片,转换为BufferedImage,调整尺寸,再输出到ByteArrayOutputStream,最后转为base64编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一更 任务需要将图片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;
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值