Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize the function of picture compression in Java

Shulou Source: shulou.com Published: 2022-06-02 08:31:54 10月01日 Update

In this issue, Xiaobian will bring you about how to realize the image compression function in Java. The article is rich in content and analyzed and described from a professional perspective. After reading this article, I hope you can gain something.

/** isoscale compressed original * @param url * Picture Network Address * @ pardestam Width Width to compress * @ pardestam Height Height to compress * @param outputDir Output Directory * @param filename File name **/ public static String thumbnail(URL url, int destWidth, int destHeight,String outputDir,String filename){ System.out.println("Image compression start"); long startTime = System.currentTimeMillis(); String returnurl =""; //compressed image location try { //read original BufferedImage BI = ImageIO.read(url); int srcWidth = BI.getWidth(); //original width int srcHeight = BI.getHeight(); //original height returnurl = outputDir+File.separatorChar+filename; OutputStream fos =new FileOutputStream(returnurl); if(srcWidth>=destWidth || srcHeight>=destWidth) { double sx = (double) destWidth / srcWidth; double sy = (double) destHeight / srcHeight; //scaling if (sx > sy) { sx = sy; destWidth = (int) (sx * srcWidth); } else { sy = sx; destHeight = (int) (sy * srcHeight); } } //SCALE_SMOOTH compression algorithm may have some impact on picture sharpness, but it is still within acceptable range Image image = BI.getScaledInstance(destWidth, destHeight, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(destWidth, destHeight,BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.setColor(Color.RED); g.drawImage(image, 0, 0, null); //Draw the processed graph g.dispose(); ImageIO.write(tag, "JPEG", fos); System.out.println("Image compression ends"); long endTime = System.currentTimeMillis(); System.out.println("Total Image Compression Time: " +(endTime-startTime)+"ms" ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnurl; } The above is how to implement the image compression function in Java shared by Xiaobian. If there is a similar doubt, please refer to the above analysis for understanding. If you want to know more about it, please pay attention to the industry information channel.

Tags: Picture original picture function content width height analysis specialty small and medium location rich content name address that is file article more sharpness directory knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL NVidia macOS Shulou Information Shulou Technology