java-将图片从URL中读出来,先压缩到500kb以下,再转换成base64

/**
     * 将图片转换为base64格式
     *
     * @param imageUrl:图片路径
     * @param sizeLimit:原图大小上限,当图片原图大小超过该值时先将图片大小 设置为该值以下再转换成base64格式,单位kb
     * @return
     */
    public static String convertImageToBase64(String imageUrl, Integer sizeLimit) throws IOException {
        //默认上限为500k
        if (sizeLimit == null) {
            sizeLimit = 500;
        }
        sizeLimit = sizeLimit * 1024;
        String base64Image;
        DataInputStream dataInputStream = null;
        ByteArrayOutputStream outputStream = null;
        ByteArrayInputStream inputStream = null;
        try {
            //从远程读取图片
            URL url = new URL(imageUrl);
            dataInputStream = new DataInputStream(url.openStream());
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            byte[] context = outputStream.toByteArray();

            //将图片数据还原为图片
            inputStream = new ByteArrayInputStream(context);
            BufferedImage image = ImageIO.read(inputStream);
            int imageSize = context.length;
            int type = image.getType();
            int height = image.getHeight();
            int width = image.getWidth();

            BufferedImage tempImage;
            //判断文件大小是否大于size,循环压缩,直到大小小于给定的值
            while (imageSize > sizeLimit) {
                //将图片长宽压缩到原来的90%
                height = new Double(height * 0.9).intValue();
                width = new Double(width * 0.9).intValue();
                tempImage = new BufferedImage(width, height, type);
                // 绘制缩小后的图
                tempImage.getGraphics().drawImage(image, 0, 0, width, height, null);
                //重新计算图片大小
                outputStream.reset();
                ImageIO.write(tempImage, "JPEG", outputStream);
                imageSize = outputStream.toByteArray().length;
            }

            //将图片转化为base64并返回
            byte[] data = outputStream.toByteArray();
            //此处一定要使用org.apache.tomcat.util.codec.binary.Base64,防止再linux上出现换行等特殊符号
            base64Image = Base64.encodeBase64String(data);
        } catch (Exception e) {
            //抛出异常
            throw e;
        } finally {
            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64Image;
    }

 

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下Java代码示例,可以将一个文件夹所有的图片转换成base64格式,并将结果保存到Excel: ```java import java.io.*; import java.util.Base64; import org.apache.poi.ss.usermodel.*; public class ImageToBase64Excel { public static void main(String[] args) { String folderPath = "C:/images"; // 图片所在文件夹路径 String excelPath = "C:/images.xlsx"; // 保存Excel文件路径 // 创建Excel工作簿 Workbook workbook = WorkbookFactory.create(new File(excelPath)); Sheet sheet = workbook.createSheet("Images"); int rowNum = 0; // 遍历文件夹的所有图片文件 File folder = new File(folderPath); File[] files = folder.listFiles(); for (File file : files) { if (file.isFile() && file.getName().toLowerCase().endsWith(".jpg")) { // 读取图片文件并转换成base64格式 byte[] imageBytes = readBytesFromFile(file); String base64String = Base64.getEncoder().encodeToString(imageBytes); // 保存base64格式到Excel Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(file.getName()); row.createCell(1).setCellValue(base64String); } } // 保存Excel文件 try (FileOutputStream outputStream = new FileOutputStream(excelPath)) { workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } } // 读取文件字节流 private static byte[] readBytesFromFile(File file) { try (FileInputStream inputStream = new FileInputStream(file)) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } return outputStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); return null; } } } ``` 该代码使用了Apache POI库来创建和操作Excel文件。在遍历文件夹的所有图片文件时,只处理以“.jpg”为后缀的文件。对于每个图片文件,读取其字节流,再将其转换成base64格式。最后,将文件名和base64格式保存到Excel文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值