io获取本地图片并进行压缩然后转换base64编码

io获取本地图片并进行压缩然后转换base64编码

 @Test
    public void  test5() throws Exception {
        String imgUrl = "http://sy1.iknowmuch.com/ishelf/imgs/upload/product/debug_esl.png";
        String imgdist = "C:\\ishelf\\imgs";
        String imgUrlFile = templateCenterService.imgUrlFile(imgdist, imgUrl);
        File distfile = new File(imgUrlFile);
        BufferedImage src = ImageIO.read(distfile);
        System.out.println("没压缩前大小:"+distfile.length());
        if(distfile.length()>=3000){
            int [] widthAndHeight = new int[2];
            widthAndHeight[0] = (int)src.getWidth(null);
            widthAndHeight[1] = (int) src.getHeight(null);
            reduceImg(imgUrlFile,widthAndHeight,(int)src.getWidth(null),(int) src.getHeight(null),null);
            System.out.println(distfile.length());
        }
        System.out.println("字节码:"+getImageBinary(imgUrlFile));
    }


    /**
     * 压缩图片
     * @param imgsrc
     * @param widthAndHeight
     * @param widthdist
     * @param heightdist
     * @param rate
     */
    public static void reduceImg(String imgsrc,int []widthAndHeight, int widthdist, int heightdist, Float rate) {
        try {
            File srcfile = new File(imgsrc);
            // 检查图片文件是否存在
            if (!srcfile.exists()) {
                System.out.println("文件不存在");
            }
            // 如果比例不为空则说明是按比例压缩
            if (rate != null && rate > 0) {
                //获得源图片的宽高存入数组中
                if (widthAndHeight == null || widthAndHeight[0] == 0 || widthAndHeight[1] == 0) {
                    return;
                } else {
                    //按比例缩放或扩大图片大小,将浮点型转为整型
                    widthdist = (int) (widthAndHeight[0] * rate);
                    heightdist = (int) (widthAndHeight[1] * rate);
                }
            }
            // 开始读取文件并进行压缩
            Image src = ImageIO.read(srcfile);

            // 构造一个类型为预定义图像类型之一的 BufferedImage
            BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);

            //绘制图像  getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像
            //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

            //创建文件输出流
            FileOutputStream out = new FileOutputStream(imgsrc);
            //将图片按JPEG压缩,保存到out中
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            //关闭文件输出流
            out.close();
        } catch (Exception ef) {
            ef.printStackTrace();
        }
    }

    public static String getImageBinary(String imageUrl) {
        String data = null;
        try {
            //int HttpResult = 0; // 服务器返回的状态
            File imageFile = new File(imageUrl);
            InputStream inStream = new FileInputStream(imageFile);
            byte[] btImg = readInputStream(inStream);
            data = Base64.encode(btImg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Java 中的 `java.util.zip` 和 `java.util.Base64` 类来实现文件的压缩转换Base64 编码。以下是一个示例代码: ```java import java.io.*; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import java.util.Base64; public class FileCompression { public static void main(String[] args) { String filePath = "path/to/your/file.txt"; // 替换为你的文件路径 String base64String = compressToBase64(filePath); System.out.println("Base64 编码: " + base64String); } public static String compressToBase64(String filePath) { try { File inputFile = new File(filePath); FileInputStream fileInputStream = new FileInputStream(inputFile); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteOutputStream); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { deflaterOutputStream.write(buffer, 0, bytesRead); } deflaterOutputStream.close(); fileInputStream.close(); byte[] compressedData = byteOutputStream.toByteArray(); byte[] base64EncodedData = Base64.getEncoder().encode(compressedData); return new String(base64EncodedData); } catch (IOException e) { e.printStackTrace(); } return null; } } ``` 在上面的示例代码中,我们首先通过 `FileInputStream` 读取文件内容,然后使用 `DeflaterOutputStream` 进行压缩。接下来,我们将压缩后的数据通过 `Base64.getEncoder().encode()` 方法进行 Base64 编码。最后,返回 Base64 编码后的字符串。 请确保将 `filePath` 替换为你要压缩的文件的实际路径。注意,这个示例只是演示了如何进行文件压缩转换Base64 编码,并未处理异常情况,你可能需要根据你的实际需求进行适当的异常处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值