java - 更改缓冲图像背景
问题描述
我正在尝试创建一个徽标大小调整器,它还会根据用户输入将徽标背景的颜色更改为白色或透明。
这可以将图像的背景颜色从透明变为白色:
BufferedImage inputImage = ImageIO.read(new File(inputImagePath)); //reads the input image
BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.TYPE_INT_ARGB); //creates the output image
Graphics2D image = outputImage.createGraphics();
image.setBackground(Color.WHITE); //sets background color to white
image.fillRect(0, 0, newWidth, newHeight);
image.drawImage(inputImage, 0, 0, newWidth, newHeight, null);
image.dispose();
String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1); //Finds what type of image it is
ImageIO.write(outputImage, formatName, new File(outputImagePath)); //Creates the output image file in correct path
}
我想如果我把它改成这个,它会将图像背景颜色从白色更改为透明,但它会保持白色。有什么帮助吗?
BufferedImage inputImage = ImageIO.read(new File(inputImagePath)); //reads the input image
BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.TYPE_INT_ARGB); //creates the output image
Graphics2D image = outputImage.createGraphics(); //Draws the actual output image
image.setComposite(AlphaComposite.Clear);
image.fillRect(0, 0, newWidth, newHeight);
image.setComposite(AlphaComposite.Src);
image.drawImage(inputImage, 0, 0, newWidth, newHeight, null); //Draws the actual output image
image.dispose();
String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1); //Finds what type of image it is
ImageIO.write(outputImage, formatName, new File(outputImagePath)); //Creates the output image file in correct path
}
我现在在想,我可能必须追踪徽标并为其本身赋予一个全新的背景,但这可能会非常困难。有什么建议吗?
解决方案
推荐阅读
- c# - 如何避免 Newtonsoft JObject.Parse 类型转换
- android - 获取 Google 签名的用户信息
- django - 在不使用 url 方法的情况下在迭代期间显示图像 url
- reactjs - React jest 测试抛出“对象作为 React 子项无效(找到:带有键 {type,props} 的对象)”
- ssh - 流浪汉禁用密码身份验证不起作用
- android - 如何调试 Firebase Android Studio 应用程序,该应用程序因权限被拒绝而上传失败?
- html - 在搜索栏 HTML 中显示图像
- ios - 赋值相关对象核心数据
- google-apps-script - onSelectionChange Google 应用脚本示例
- c - 在调用者堆栈上分配的内联函数、宏和其他解决方案