Java圖片壓縮三種高效壓縮方案詳細解析
一、基于OpenCV的智能尺寸壓縮
java public static void extracted2() { '
String path = "C:\test.jpg";
String savePath = "D:\compressed.jpg";
int maxWidth = 800;
int maxHeight = 600;
compressImage(new File(path), new File(savePath), maxWidth, maxHeight);
}
compressImage 寫法為kotlin語法法,需要自己轉(zhuǎn)換
fun compressImage(inputFile: File, outputFile: File, maxWidth: Int, maxHeight: Int) {
try {
val image = ImageIO.read(inputFile)
val originalWidth = image.width
val originalHeight = image.height
var newWidth = originalWidth
var newHeight = originalHeight
// 計算新的寬度和高度,保持比例
if (originalWidth > maxWidth || originalHeight > maxHeight) {
val ratio = Math.min(maxWidth.toDouble() / originalWidth, maxHeight.toDouble() / originalHeight)
newWidth = (originalWidth * ratio).toInt()
newHeight = (originalHeight * ratio).toInt()
}
val resizedImage = BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB)
resizedImage.createGraphics().apply {
drawImage(image.getScaledInstance(newWidth, newHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null)
dispose()
}
// 確保輸出目錄存在
val outputPath: Path = Paths.get(outputFile.parent)
if (!Files.exists(outputPath)) {
Files.createDirectories(outputPath)
}
ImageIO.write(resizedImage, "jpg", outputFile)
} catch (e: IOException) {
e.printStackTrace()
}
}
技術(shù)亮點:
- 動態(tài)尺寸調(diào)整:通過設(shè)置最大寬高(800x600),自動保持原圖比例
- OpenCV加持:使用Imgproc.resize()進行高質(zhì)量縮放
- 跨平臺支持:需配置OpenCV本地庫(System.loadLibrary)
適用場景:
- 移動端圖片展示
- 用戶頭像上傳
二、JPEG質(zhì)量參數(shù)壓縮
java public static void extracted4() {
for (int i = 1; i <=10; i++) {
float quality = 0.1f * i;
compressImage(inputFile, outputFile, quality);
}
}
public static void compressImage(File inputFile, File outputFile, float quality) throws IOException {
// 讀取圖片
BufferedImage image = ImageIO.read(inputFile);
// 獲取圖片寫入器
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("webp");
ImageWriter writer = writers.next();
// 設(shè)置寫入器的輸出目標(biāo)
ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
writer.setOutput(ios);
// 創(chuàng)建圖片寫入器配置
IIOImage imageIO = new IIOImage(image, null, null);
ImageWriteParam param = writer.getDefaultWriteParam();
// 設(shè)置壓縮質(zhì)量
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
}
// 寫入圖片
writer.write(null, imageIO, param);
// 關(guān)閉資源
ios.close();
writer.dispose();
}
關(guān)鍵技術(shù):
- 質(zhì)量梯度測試:從0.1到1.0進行10級壓縮測試
- 無損壓縮支持:通過ImageWriteParam控制壓縮模式
- 視覺質(zhì)量平衡:找到文件大小與清晰度的最佳平衡點
壓縮效果對比:
| 質(zhì)量參數(shù) | 文件大小 | 清晰度 |
|---|---|---|
| 0.3 | 45KB | 可接受 |
| 0.7 | 120KB | 良好 |
| 1.0 | 350KB | 無損 |
三、WebP高效格式轉(zhuǎn)換
public static void extracted6() {
String path = "C:\\Users\\美眾\\Pictures\\test2.jpg";
for (int i = 1; i <=10; i++) {
float quality = 0.0f + i * 0.1f;
System.out.println("quality:" + quality);
String savePath = "D:\\save\\test2-webp-"+quality+".jpg";
File inputFile = new File(path); // 原始圖片文件
File outputFile = new File(savePath);
try {
jpg2webp(inputFile, outputFile,quality);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void jpg2webp(File oldfile, File newfile,float quality){
try {
// 獲取原始文件的編碼
BufferedImage image = ImageIO.read(oldfile);
// 創(chuàng)建WebP ImageWriter實例
ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
// 配置編碼參數(shù)
WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
// 設(shè)置壓縮模式
writeParam.setCompressionMode(WebPWriteParam.MODE_EXPLICIT);
System.out.println("getCompressionTypes:"+JSON.toJSON(writeParam.getCompressionTypes()));
// "Lossy"-有損,"Lossless"-無損
writeParam.setCompressionType(writeParam.getCompressionTypes()[0]);
writeParam.setCompressionQuality(quality);
// 配置ImageWriter輸出
writer.setOutput(new FileImageOutputStream(newfile));
// 進行編碼,重新生成新圖片
writer.write(null, new IIOImage(image, null, null), writeParam);
System.out.println("jpg文件轉(zhuǎn)成webp格式成功");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
核心優(yōu)勢:
- 壓縮率提升:比JPEG節(jié)省25-35%空間
- 透明通道支持:支持Alpha通道透明效果
- 漸進式加載:支持漸進式解碼加載
性能對比:
| 格式 | 質(zhì)量0.8 | 加載速度 | 兼容性 |
|---|---|---|---|
| JPEG | 150KB | 快 | 100% |
| WebP | 95KB | 較快 | 95%+ |
四、方案選型建議
- 移動端優(yōu)先:WebP + 質(zhì)量壓縮(0.6-0.8)
- 用戶上傳處理:尺寸壓縮 + JPEG質(zhì)量0.7
- 專業(yè)圖庫存儲:OpenCV雙算法校驗(直方圖對比+尺寸壓縮)
總結(jié)
到此這篇關(guān)于Java圖片壓縮三種高效壓縮方案的文章就介紹到這了,更多相關(guān)Java圖片高效壓縮內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot使用maven實現(xiàn)多環(huán)境運行和打包問題
這篇文章主要介紹了springboot使用maven實現(xiàn)多環(huán)境運行和打包問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
基于Java?SpringBoot的前后端分離信息管理系統(tǒng)的設(shè)計和實現(xiàn)
當(dāng)今社會,人才的流動速度大大增加,因此也對黨建工作的管理層面工作帶來了空前且復(fù)雜的挑戰(zhàn),從而使得如何高效的開展管理黨建工作成為了亟待解決的問題。本文將介紹通過Java?SpringBoot實現(xiàn)前后端分離信息管理系統(tǒng),感興趣的同學(xué)可以了解一下2021-11-11
Spring Data JPA 設(shè)置字段默認值方式
這篇文章主要介紹了Spring Data JPA設(shè)置字段默認值方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
JavaEE開發(fā)之SpringMVC中的自定義消息轉(zhuǎn)換器與文件上傳
本篇文章主要介紹了SpringMVC的相關(guān)知識。同時也會介紹到j(luò)s、css這些靜態(tài)文件的加載配置,以及服務(wù)器推送的兩種實現(xiàn)方式并且給出了兩者的區(qū)別。下面跟著小編一起來看下吧2017-04-04
Spring Boot攔截器Interceptor與過濾器Filter深度解析(區(qū)別、實現(xiàn)與實戰(zhàn)指南)
對比SpringBoot攔截器與過濾器在執(zhí)行順序、作用范圍、異常處理等核心差異,指導(dǎo)開發(fā)實踐與選型策略,強調(diào)攔截器適合Web層通用邏輯,過濾器用于底層處理,建議結(jié)合APM工具優(yōu)化性能,感興趣的朋友跟隨小編一起看看吧2025-06-06
Java中的HashMap為什么會產(chǎn)生死循環(huán)
這篇文章主要介紹了Java中的HashMap為什么會產(chǎn)生死循環(huán),HashMap?死循環(huán)是一個比較常見、比較經(jīng)典的問題,下面文章我們就來徹底理解死循環(huán)的原因。需要的小伙伴可以參考一下2022-05-05
RocketMQ消息存儲文件的加載與恢復(fù)機制源碼分析
這篇文章主要介紹了RocketMQ源碼分析之消息存儲文件的加載與恢復(fù)機制詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05

