Java裁剪压缩PNG图片,透明背景色变黑问题解决
生活随笔
收集整理的這篇文章主要介紹了
Java裁剪压缩PNG图片,透明背景色变黑问题解决
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.gblfy.test;import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;import javax.imageio.ImageIO;/*** 圖片工具類*/
public class ImageUtil {/*** 裁剪PNG圖片工具類** @param fromFile 源文件* @param toFile 裁剪后的文件* @param outputWidth 裁剪寬度* @param outputHeight 裁剪高度* @param proportion 是否是等比縮放*/public static void resizePng(File fromFile, File toFile, int outputWidth, int outputHeight,boolean proportion) {try {BufferedImage bi2 = ImageIO.read(fromFile);int newWidth;int newHeight;// 判斷是否是等比縮放if (proportion) {// 為等比縮放計算輸出的圖片寬度及高度double rate1 = ((double) bi2.getWidth(null)) / (double) outputWidth + 0.1;double rate2 = ((double) bi2.getHeight(null)) / (double) outputHeight + 0.1;// 根據縮放比率大的進行縮放控制double rate = rate1 < rate2 ? rate1 : rate2;newWidth = (int) (((double) bi2.getWidth(null)) / rate);newHeight = (int) (((double) bi2.getHeight(null)) / rate);} else {newWidth = outputWidth; // 輸出的圖片寬度newHeight = outputHeight; // 輸出的圖片高度}BufferedImage to = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g2d = to.createGraphics();to = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight,Transparency.TRANSLUCENT);g2d.dispose();g2d = to.createGraphics();@SuppressWarnings("static-access")Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING);g2d.drawImage(from, 0, 0, null);g2d.dispose();ImageIO.write(to, "png", toFile);} catch (Exception e) {e.printStackTrace();}}/*** 測試*/public static void main(String[] args) throws Exception {File fromFile = new File("D:\\22\\iconPath\\22.png");File toFile = new File("D:\\22\\iconPath\\2255555.png");resizePng(fromFile, toFile, 100, 100, false);//根據實際圖片大小修改 水印圖片的大小 動態適配// resizePng(fromFile, toFile, (int) (1244 * 0.71), (int) (1684 * 0.18), false);}
}
總結
以上是生活随笔為你收集整理的Java裁剪压缩PNG图片,透明背景色变黑问题解决的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: KeeperErrorCode = Un
- 下一篇: 使用Axios拦截器打印前端请求日志和后