Recently, the company needed XXX certification to upload the specific screenshots of the test case function, and found that there was a size limit, so we compressed the pictures for a brief record.

Size before compression:

Compressed size:

Specific code implementation:

Main method test:

 public static void main(String[] args) throws IOException {
        String modpath = "C:\ Users\ Administrator\ Desktop\\ test\";
        getFiles("C:\ Users\ Administrator\ Desktop\\ list of test Cases", modpath, 160);// Compress the image to 100 width
    }
Copy the code

File size handling

/ * * *@paramSrcPath Original image path *@paramImage path after desPath resizes *@paramWidth Converted image width *@paramHeight converted image height */
    public static void resizeImage(String srcPath, String desPath, int width, int height) throws IOException {


        File srcFile = new File(srcPath);
        Image srcImg = ImageIO.read(srcFile);
        BufferedImage buffImg = null;
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        // Images modified using TYPE_INT_RGB will change color
        buffImg.getGraphics().drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0.0.null);
        String filePath="";
        if (srcFile.getName().contains("#")) {
             filePath = srcFile.getName().replace("#"."");
        }else{
            filePath=srcFile.getName();
        }
        ImageIO.write(buffImg, "PNG".new File(desPath + filePath));
    }
Copy the code

Get directory file information

/ * * *@paramScaleSize Image modification scale, target width */
    public static void getFiles(String path, String modPath, int scaleSize) throws IOException {
        ArrayList<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        // loop through the images in the directory
        for (int i = 0; i < tempList.length; i++) {
            String filePath = tempList[i].getName();
            if (tempList[i].isFile()) {

                System.out.println("Document:" + filePath + "-" + tempList[i].getAbsolutePath().replaceAll("\ \ \ \"."/"));
                String[] imagePath = tempList[i].getAbsolutePath().replaceAll("\ \ \ \"."/").split("/");
                String imageNumber = null;
                FileUtil.resizeImage(tempList[i].getAbsolutePath().replaceAll("\ \ \ \"."/"), modPath, 160.160);
                files.add(tempList[i].toString());
            }
            if (tempList[i].isDirectory()) {
                  System.out.println("Folder:" + tempList[i]);
            }
        }
        System.out.println(path + "Number of files:" + files.size());
    }
Copy the code

Console directory compressed successfully saved to drive letter:

Everyone likes, likes, likes, comments, clocked the article updated 112/365 days