Java如何處理圖片保存之后變紅色的問題
問題
原圖如下

上傳之后效果如下

馬賽克是我打的,別人家的logo,避免廣告之嫌,系統(tǒng)審核不過
然而其他圖片并不存在這個問題,如

這張,不存在這樣的問題
兩張圖片不同點在于正常的為jpg,變色的為png
后面經(jīng)過不同的嘗試后發(fā)現(xiàn),透明的PNG圖、改alpha通道或四色圖等都會引起以上問題
解決辦法
有兩種,這里分享比較好用的一種,方便快捷,復(fù)制粘貼就能用
// 這里是直接根據(jù)url讀取圖片
public static BufferedImage getBufferedImage(String imgUrl) throws MalformedURLException {
URL url = new URL(imgUrl);
ImageIcon icon = new ImageIcon(url);
Image image = icon.getImage();
// 如果是從本地加載,就用這種方式,沒親自測試過
// Image src=Toolkit.getDefaultToolkit().getImage(filePath);
// This code ensures that all the pixels in the image are loaded
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null),
image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null),
image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}我的是在原代碼中,將
bi = ImageIO.read(inStream);
替換為
bi = getBufferedImage(inFile.getPath());
具體如下

最終效果

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot之ApplicationRunner解析(spring容器啟動完成執(zhí)行的類)
這篇文章主要介紹了SpringBoot之ApplicationRunner解析(spring容器啟動完成執(zhí)行的類),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
SpringBoot整合MyBatis實現(xiàn)CRUD操作項目實踐
本文主要介紹了SpringBoot整合MyBatis實現(xiàn)CRUD操作項目實踐,如何實現(xiàn)數(shù)據(jù)庫的CRUD創(chuàng)建、讀取、更新、刪除操作,具有一定的參考價值,感興趣的可以了解一下2024-02-02
SpringCache緩存抽象之CacheManager與自定義鍵生成方式
本文將深入探討Spring Cache的核心組件CacheManager及自定義鍵生成策略,幫助開發(fā)者掌握緩存配置與優(yōu)化技巧,從而構(gòu)建高效可靠的緩存系統(tǒng),希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
連續(xù)調(diào)用多個外部系統(tǒng)寫接口保證數(shù)據(jù)一致性的思路
今天小編就為大家分享一篇關(guān)于連續(xù)調(diào)用多個外部系統(tǒng)寫接口保證數(shù)據(jù)一致性的思路,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12

