Java图片压缩详解编程语言

package com.test; 
 
import com.sun.image.codec.jpeg.JPEGCodec; 
import com.sun.image.codec.jpeg.JPEGImageEncoder; 
import org.junit.Test; 
import javax.imageio.ImageIO; 
import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
 
/** 
 *图片压缩 
 */ 
public class ImageTest { 
     
    private Image img; 
    private int width; 
    private int height; 
 
    @Test 
    public void test(){ 
        try{ 
            //压缩开始 
            ImageTest imgCom = new ImageTest("D://1.png"); 
            imgCom.resizeFix(400, 400,"D://2.png"); 
            //压缩结束 
        }catch (Exception e){ 
            e.printStackTrace(); 
        } 
    } 
 
    /** 
     * 构造函数 
     * @param fileName 图片路径 
     * @throws IOException 
     */ 
    public ImageTest(String fileName) throws IOException { 
        // 读入文件 
        File file = new File(fileName); 
        // 构造Image对象 
        img = ImageIO.read(file); 
        // 得到源图宽 
        width = img.getWidth(null); 
        // 得到源图长 
        height = img.getHeight(null); 
    } 
 
    /** 
     * 按照宽度还是高度进行压缩 
     * @param w int 最大宽度 
     * @param h  int 最大高度 
     * @param filePath 图片路径 
     * @throws IOException 
     */ 
    public void resizeFix(int w, int h,String filePath) throws IOException { 
        if (width / height > w / h) { 
            resizeByWidth(w,filePath); 
        } else { 
            resizeByHeight(h,filePath); 
        } 
    } 
 
    /** 
     * 以宽度为基准,等比例放缩图片 
     * @param w int 新宽度 
     * @param filePath 图片路径 
     * @throws IOException 
     */ 
    public void resizeByWidth(int w,String filePath) throws IOException { 
        int h = (int) (height * w / width); 
        resize(w, h,filePath); 
    } 
 
    /** 
     * 以高度为基准,等比例缩放图片 
     * @param h int 新高度 
     * @param filePath 图片路径 
     * @throws IOException 
     */ 
    public void resizeByHeight(int h,String filePath) throws IOException { 
        int w = (int) (width * h / height); 
        resize(w, h,filePath); 
    } 
 
    /** 
     * 强制压缩/放大图片到固定的大小 
     * @param w int 新宽度 
     * @param h int 新高度 
     * @param filePath 
     * @throws IOException 
     */ 
    public void resize(int w, int h,String filePath) throws IOException { 
        // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢 
        BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); 
        // 绘制缩小后的图 
        image.getGraphics().drawImage(img, 0, 0, w, h, null); 
        File destFile = new File(filePath); 
        // 输出到文件流 
        FileOutputStream out = new FileOutputStream(destFile); 
        // 可以正常实现bmp、png、gif转jpg 
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 
        // JPEG编码 
        encoder.encode(image); 
        out.close(); 
    } 
} 

  

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/18557.html

(0)
上一篇 2021年7月19日 21:14
下一篇 2021年7月19日 21:14

相关推荐

发表回复

登录后才能评论