经典重庆

标题: java图片无损压缩 [打印本页]

作者: lianrangsiw    时间: 2020-12-29 00:12
标题: java图片无损压缩

  public static boolean compressPic(String srcFilePath, String descFilePath) throws IOException  {商业图片的相关问题可以到网站了解下,我们是业内领域专业的平台,您如果有需要可以咨询,相信可以帮到您,值得您的信赖!!

  File file =null;

  BufferedImage src =null;

  FileOutputStream out=null;

  // 指定写图片的方式为 jpg

  ImageWriter  imgWrier=ImageIO.getImageWritersByFormatName("jpg").next();

  ImageWriteParam imgWriteParams =new ImageWriteParam(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)));

  try {

  if (StringUtils.isEmpty(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;

  }




欢迎光临 经典重庆 (http://bbs.jdcq.net/) Powered by Discuz! X3.1