1. 程式人生 > >Java圖片處理---尺寸不變,大小壓縮

Java圖片處理---尺寸不變,大小壓縮

尺寸不變,大小壓縮

  public static boolean compressPic(String srcFilePath, String descFilePath) throws IOException {
        File file = null;
        BufferedImage src = null;
        FileOutputStream out = null;
        ImageWriter imgWrier;
        ImageWriteParam imgWriteParams;

        // 指定寫圖片的方式為 jpg
        imgWrier = ImageIO.getImageWritersByFormatName("jpg"
).next(); imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam( null); // 要使用壓縮,必須指定壓縮方式為MODE_EXPLICIT imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT); // 這裡指定壓縮的程度,引數qality是取值0~1範圍內, imgWriteParams.setCompressionQuality((float
)1); imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED); ColorModel colorModel = ImageIO.read(new File(srcFilePath)).getColorModel();// ColorModel.getRGBdefault(); // 指定壓縮時使用的色彩模式 // imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier( // colorModel, colorModel.createCompatibleSampleModel(16, 16)));
imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier( colorModel, colorModel.createCompatibleSampleModel(16, 16))); try { if (isBlank(srcFilePath)) { return false; } else { file = new File(srcFilePath); System.out.println(file.length()); src = ImageIO.read(file); out = new FileOutputStream(descFilePath); imgWrier.reset(); // 必須先指定 out值,才能呼叫write方法, ImageOutputStream可以通過任何 // OutputStream構造 imgWrier.setOutput(ImageIO.createImageOutputStream(out)); // 呼叫write方法,就可以向輸入流寫圖片 imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams); out.flush(); out.close(); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } public static boolean isBlank(String string) { if (string == null || string.length() == 0 || string.trim().equals("")) { return true; } return false; }