本文實例為大家分享了java實現圖片壓縮的相關代碼,供大家參考,具體內容如下
import java.awt.Image;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream; import javax.imageio.ImageIO; public class ImageProcess { /** * 圖片*/ private Image img; /** * 寬度*/ private int width; /** * 高度*/ private int height; /** * 文件格式*/ private String imageFormat; /** * 構造函數* @throws Exception */ public ImageProcess(InputStream in,String fileName) throws Exception{ //構造Image對象img = ImageIO.read(in); //得到源圖寬width = img.getWidth(null); //得到源圖長height = img.getHeight(null); //文件格式imageFormat = fileName.substring(fileName.lastIndexOf(".")+1); } /** * 按照寬度還是高度進行壓縮* @param w int 最大寬度* @param h int 最大高度*/ public byte[] resizeFix(int w, int h) throws IOException { if (width / height > w / h) { return resizeByWidth(w); } else { return resizeByHeight(h); } } /** * 以寬度為基準,等比例放縮圖片* @param w int 新寬度*/ public byte[] resizeByWidth(int w) throws IOException { int h = (int) (height * w / width); return resize(w, h); } /** * 以高度為基準,等比例縮放圖片* @param h int 新高度*/ public byte[] resizeByHeight(int h) throws IOException { int w = (int) (width * h / height); return resize(w, h); } /** * 強制壓縮/放大圖片到固定的大小* @param w int 新寬度* @param h int 新高度*/ public byte[] resize(int w, int h) throws IOException { // SCALE_SMOOTH 的縮略算法生成縮略圖片的平滑度的優先級比速度高生成的圖片質量比較好但速度慢BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); image.getGraphics().drawImage(img, 0, 0, w, h, null); // 繪製縮小後的圖ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, imageFormat, baos); return baos.toByteArray(); } }以上就是本文的全部內容,希望對大家的學習有所幫助,輕鬆實現圖片壓縮操作。