本地上传图片 实现图片缩放和图片复制改名

  
if (file.getSize() > 32000) {  
                    String copyFilePath = nFilePath.replaceAll("." +              MyUtilFile.getInstance().getSuffix(nFilePath), "32k") + "." + MyUtilFile.getInstance().getSuffix(nFilePath);
                    File copyFile = new File(copyFilePath);

                    if (!copyFile.getParentFile().exists()) {
                        copyFile.getParentFile().mkdirs();
                    }

                    zoomImage(nFilePath, copyFilePath, 32);
                }
                else {
                    String copyFilePath = nFilePath.replaceAll("." + MyUtilFile.getInstance().getSuffix(nFilePath), "32k") + "." + MyUtilFile.getInstance().getSuffix(nFilePath);
                    File copyFile = new File(copyFilePath);

                    if (!copyFile.getParentFile().exists()) {
                        copyFile.getParentFile().mkdirs();
                    }
                    FileInputStream fis = new FileInputStream(nFilePath);
                    FileOutputStream fos = new FileOutputStream(copyFilePath);

                    // 读取和写入信息
                    int len = 0;
                    while ((len = fis.read()) != -1) {
                        fos.write(len);
                    }
                    // 关闭流  先开后关  后开先关
                    fos.close();
                    fis.close();

                }

以上的代码 进行解释 file是前端的MultipartFile文件,所以我要判断他的大小是否在32000Byte以内,如果小于32000Byte就进行复制并在原来的文件名上进行更改,改为源文件名+32kb+文件后缀名。大小大于32000Byte,进行文件缩放将文件缩放到32kb以内。

    //copy file
    public static void zoomImage(String src, String dest, Integer size) throws Exception {
        File srcFile = new File(src);
        File destFile = new File(dest);

        long fileSize = srcFile.length();
        if (fileSize < size * 1024) {   //文件大于size k时,才进行缩放,注意:size以K为单位
            return;
        }
        Double rate = (size * 1024 * 0.8) / fileSize; // 获取长宽缩放比例

        BufferedImage bufImg = ImageIO.read(srcFile);
        Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), bufImg.SCALE_SMOOTH);

        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp, dest.substring(dest.lastIndexOf(".") + 1), destFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

以上是缩放的代码 你可以直接去用。 希望对你有点帮助。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值