解決java壓縮圖片透明背景變黑色的問題
更新時(shí)間:2014年04月15日 09:01:36 作者:
這篇文章主要介紹了解決java壓縮圖片透明背景變黑色的問題,需要的朋友可以參考下
復(fù)制代碼 代碼如下:
public class Picture {
// TODO Auto-generated constructor stub
public static void resizePNG(String fromFile, String toFile, int outputWidth, int outputHeight,boolean proportion) {
try {
File f2 = new File(fromFile);
BufferedImage bi2 = ImageIO.read(f2);
int newWidth;
int newHeight;
// 判斷是否是等比縮放
if (proportion == true) {
// 為等比縮放計(jì)算輸出的圖片寬度及高度
double rate1 = ((double) bi2.getWidth(null)) / (double) outputWidth + 0.1;
double rate2 = ((double) bi2.getHeight(null)) / (double) outputHeight + 0.1;
// 根據(jù)縮放比率大的進(jìn)行縮放控制
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();
Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING);
g2d.drawImage(from, 0, 0, null);
g2d.dispose();
ImageIO.write(to, "png", new File(toFile));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
System.out.println("Start");
resizePNG("C:\\Documents and Settings\\Administrator\\桌面\\8d9e9c82d158ccbf8b31059319d8bc3eb035414e.jpg", "C:\\Documents and Settings\\Administrator\\桌面\\ell.png",200, 100,true);
System.out.println("OK");
}
}
相關(guān)文章
SpringBoot ApplicationContextAware拓展接口使用詳解
當(dāng)一個(gè)類實(shí)現(xiàn)了這個(gè)接口(ApplicationContextAware)之后,這個(gè)類就可以方便獲得ApplicationContext中的所有bean。換句話說,就是這個(gè)類可以直接獲取spring配置文件中,所有有引用到的bean對象2023-04-04Java內(nèi)存釋放實(shí)現(xiàn)代碼案例
這篇文章主要介紹了Java內(nèi)存釋放實(shí)現(xiàn)代碼案例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12java實(shí)現(xiàn)IP地址轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)IP地址轉(zhuǎn)換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11idea導(dǎo)入工程時(shí)不能導(dǎo)入maven項(xiàng)目不能加入tomcatServer的原因
這篇文章主要介紹了idea導(dǎo)入工程時(shí)不能導(dǎo)入maven項(xiàng)目不能加入tomcatServer的原因及解決方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09