Java图片压缩及解决遇到压缩时出现黑底的问题
生活随笔
收集整理的這篇文章主要介紹了
Java图片压缩及解决遇到压缩时出现黑底的问题
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
? ?在項(xiàng)目中有個(gè)需求是將圖片和其他文件合并,最后輸出為一個(gè)文件,我在大佬們的幫助下找到合適的壓縮工具類來實(shí)現(xiàn)壓縮,并做如下總結(jié):?
? ? ?方案一
package com.example.cn.service;import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; import lombok.extern.slf4j.Slf4j;import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.MathContext; import java.util.ArrayList;@Slf4j public class ImageHelper { /**** 將圖片縮放到指定的高度或者寬度* @param sourceImagePath 圖片源地址* @param destinationPath 壓縮完圖片的地址* @param width 縮放后的寬度* @param height 縮放后的高度* @param auto 是否自動保持圖片的原高寬比例* @param format 圖圖片格式 例如 jpg*/public static void scaleImageWithParams(String sourceImagePath,String destinationPath, int width, int height, boolean auto, String format) {try {File file = new File(sourceImagePath);BufferedImage bufferedImage = null;bufferedImage = ImageIO.read(file);if (auto) {ArrayList<Integer> paramsArrayList = getAutoWidthAndHeight(bufferedImage, width, height);width = paramsArrayList.get(0);height = paramsArrayList.get(1);}Image image = bufferedImage.getScaledInstance(width, height,Image.SCALE_DEFAULT);BufferedImage outputImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics graphics = outputImage.getGraphics();graphics.drawImage(image, 0, 0, null);graphics.dispose();ImageIO.write(outputImage, format, new File(destinationPath));} catch (Exception e) {log.error("壓縮圖片出現(xiàn)未知錯(cuò)誤!", e);}} }?
? ? ?方案二
package com.hand.hcf.app.expense.pdf.util; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.io.File; import java.io.FileOutputStream; import java.io.IOException;import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter;public class ImageUtil {public static boolean compressPic(String srcFilePath, String descFilePath) throws IOException {File file = null;BufferedImage src = null;FileOutputStream out = null;ImageWriter imgWrier;ImageWriteParam imgWriteParams;// 指定寫圖片的方式為 jpgimgWrier = ImageIO.getImageWritersByFormatName("jpg").next();imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);// 要使用壓縮,必須指定壓縮方式為MODE_EXPLICITimgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);// 這里指定壓縮的程度,參數(shù)qality是取值0~1范圍內(nèi),imgWriteParams.setCompressionQuality((float) 1);imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);// ColorModel colorModel =ImageIO.read(new File(srcFilePath)).getColorModel();//ColorModel colorModel =ColorModel.getRGBdefault();// 指定壓縮時(shí)使用的色彩模式imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));try {if (isBlank(srcFilePath)) {return false;} else {file = new File(srcFilePath);System.out.println(file.length());src = ImageIO.read(file);int width = src.getWidth();int height = src.getHeight();out = new FileOutputStream(descFilePath);imgWrier.reset();// 必須先指定 out值,才能調(diào)用write方法, ImageOutputStream可以通過任何// OutputStream構(gòu)造imgWrier.setOutput(ImageIO.createImageOutputStream(out));// 調(diào)用write方法,就可以向輸入流寫圖片int w=(int)width;int h=(int)height;imgWrier.write(null, new IIOImage(src, null, null),imgWriteParams);out.flush();out.close();}} catch (Exception e) {e.printStackTrace();return false;}return true;}public static boolean isBlank(String string) {if (string == null || string.length() == 0 || string.trim().equals("")) {return true;}return false;} }效果展示:
?
?如果在壓縮過程中出現(xiàn)如上黑底的情況,指定壓縮的圖片類型,需要添加如下代碼:
指定fillReact(0,0,w,h),把圖片重新draw一次,黑底問題解決。
BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );image.getGraphics().fillRect( 0, 0 , w, h);image.getGraphics().drawImage(src, 0, 0, w, h, null);?
效果如下:
?
附上解決黑底的完整代碼:
package com.hand.hcf.app.expense.pdf.util; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.io.File; import java.io.FileOutputStream; import java.io.IOException;import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter;public class ImageUtil {public static boolean compressPic(String srcFilePath, String descFilePath) throws IOException {File file = null;BufferedImage src = null;FileOutputStream out = null;ImageWriter imgWrier;ImageWriteParam imgWriteParams;// 指定寫圖片的方式為 jpgimgWrier = ImageIO.getImageWritersByFormatName("jpg").next();imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);// 要使用壓縮,必須指定壓縮方式為MODE_EXPLICITimgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);// 這里指定壓縮的程度,參數(shù)qality是取值0~1范圍內(nèi),imgWriteParams.setCompressionQuality((float) 1);imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);// ColorModel colorModel =ImageIO.read(new File(srcFilePath)).getColorModel();//ColorModel colorModel =ColorModel.getRGBdefault();// 指定壓縮時(shí)使用的色彩模式imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));try {if (isBlank(srcFilePath)) {return false;} else {file = new File(srcFilePath);System.out.println(file.length());src = ImageIO.read(file);int width = src.getWidth();int height = src.getHeight();out = new FileOutputStream(descFilePath);imgWrier.reset();// 必須先指定 out值,才能調(diào)用write方法, ImageOutputStream可以通過任何// OutputStream構(gòu)造imgWrier.setOutput(ImageIO.createImageOutputStream(out));// 調(diào)用write方法,就可以向輸入流寫圖片int w=(int)width;int h=(int)height;BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );image.getGraphics().fillRect( 0, 0 , w, h);image.getGraphics().drawImage(src, 0, 0, w, h, null);imgWrier.write(null, new IIOImage(image, null, null),imgWriteParams);out.flush();out.close();}} catch (Exception e) {e.printStackTrace();return false;}return true;}public static boolean isBlank(String string) {if (string == null || string.length() == 0 || string.trim().equals("")) {return true;}return false;} }?
如果還不能解決黑底問題,請嘗試更改imageType類型。
?public BufferedImage(int width,int height,int imageType);
?
?
參考博客:?
https://blog.csdn.net/u012081441/article/details/80419145
https://blog.csdn.net/monitor1394/article/details/6087583
總結(jié)
以上是生活随笔為你收集整理的Java图片压缩及解决遇到压缩时出现黑底的问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL 怎么保证备份数据的一致性?
- 下一篇: [Study]JavaWeb