1. 程式人生 > >java採用降低圖片解析度大小來壓縮圖片大小

java採用降低圖片解析度大小來壓縮圖片大小

我看了網上大多數對圖片的壓縮都是基於對圖片width和hight進行裁剪來降低圖片實際大小,但這種方式容易導致圖片內容的丟失,所以推薦大家採用以下這種方式

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.IIOImage
; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Picdownload { private final static Logger logger = LoggerFactory.getLogger(Picdownload.class); /** * 壓縮圖片 * @param file * @param qality 引數qality是取值0~1範圍內 代表壓縮的程度 * @return * @throws IOException */
public static File compressPictureByQality(File file,float qality) throws IOException { BufferedImage src = null; FileOutputStream out = null; ImageWriter imgWrier; ImageWriteParam imgWriteParams; logger.info("開始設定壓縮圖片引數"); // 指定寫圖片的方式為 jpg imgWrier = ImageIO.getImageWritersByFormatName
("jpg").next(); imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam( null); // 要使用壓縮,必須指定壓縮方式為MODE_EXPLICIT imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT); // 這裡指定壓縮的程度,引數qality是取值0~1範圍內, imgWriteParams.setCompressionQuality(qality); imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED); ColorModel colorModel =ImageIO.read(file).getColorModel();// ColorModel.getRGBdefault(); imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier( colorModel, colorModel.createCompatibleSampleModel(32, 32))); logger.info("結束設定壓縮圖片引數"); if (!file.exists()) { logger.info("Not Found Img File,檔案不存在"); throw new FileNotFoundException("Not Found Img File,檔案不存在"); } else { logger.info("圖片轉換前大小"+file.length()+"位元組"); src = ImageIO.read(file); out = new FileOutputStream(file); 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(); logger.info("圖片轉換後大小"+file.length()+"位元組"); return file; } } }