Java如何處理圖片保存之后變紅色的問題
更新時間:2023年11月18日 10:05:25 作者:請告訴他
這篇文章主要介紹了Java如何處理圖片保存之后變紅色的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
問題
原圖如下

上傳之后效果如下

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

這張,不存在這樣的問題
兩張圖片不同點在于正常的為jpg,變色的為png
后面經過不同的嘗試后發(fā)現,透明的PNG圖、改alpha通道或四色圖等都會引起以上問題
解決辦法
有兩種,這里分享比較好用的一種,方便快捷,復制粘貼就能用
// 這里是直接根據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());
具體如下

最終效果

總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring AI 實現 STDIO和SSE MCP Server的過
STDIO方式是基于進程間通信,MCP Client和MCP Server運行在同一主機,主要用于本地集成、命令行工具等場景,這篇文章主要介紹了Spring AI 實現 STDIO和SSE MCP Server,需要的朋友可以參考下2025-05-05
PowerJob的IdGenerateService工作流程源碼解讀
這篇文章主要為大家介紹了PowerJob的IdGenerateService工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01

