Java how to set jpg quality

后端 未结 3 404
既然无缘
既然无缘 2021-01-12 02:25

Just wanting to get some code edited so that the output jpg quality isn\'t the default low quality setting that

try
        {
            ImageIO.write(var6         


        
3条回答
  •  孤独总比滥情好
    2021-01-12 02:53

    I came across a similar problem and the answer was not very clear to me, since at the time i did not have a knowledge on ImageIO, so to the people like me that came across this post i made a example.

    try {
                
                //  Image to be altered 
                BufferedImage imagem = ImageIO.read(new File("c://nota.jpg"));
                
                //  The output image
                File outPutImage = new File("c://nota2.jpg");
                
                //  Encapsulate the outPut image
                ImageOutputStream  ios =  ImageIO.createImageOutputStream(outPutImage);
                
                //  List of ImageWritre's for jpeg format 
                Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
                
                //  Capture the first ImageWriter
                ImageWriter writer = iter.next();
                
                //  define the o outPut file to the write
                writer.setOutput(ios);
    
                //  Here you define the changes you wanna make to the image
                ImageWriteParam iwParam = writer.getDefaultWriteParam();
                iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwParam.setCompressionQuality(.90f);
    
                //  Compression and saving to file the altered image
                writer.write(null, new IIOImage(imagem, null, null), iwParam);
                
                writer.dispose();               
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
    

    If you know of a easier way or you found out something wrong in my comments or code, please let me know in the comments so i can alter.

提交回复
热议问题