Java 图片处理 白底黑字
原图:
、
效果:
代码:
public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new FileInputStream("C:\\Users\\新建文件夹\\2925.jpg"));
BufferedImage images=replaceWithWhiteColor(image);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(images,"png",out);
byte[] bb = out.toByteArray();
// 获取当前时间戳设置为文件名避免文件名重复
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
String date = df.format(new Date())
//存放图片地址及文件名
String img_dz="C:\\"+date+".png";
BufferedWriter bw=new BufferedWriter(new FileWriter(img_dz));
File files = new File(img_dz);
FileOutputStream fops = new FileOutputStream(files);
fops.write(bb);
fops.flush();
fops.close();
}
//处理图片杂色
public static BufferedImage replaceWithWhiteColor(BufferedImage bi) {
int[] rgb = new int[3];
int width = bi.getWidth();
int height = bi.getHeight();
int minx = bi.getMinX();
int miny = bi.getMinY();
/*
* 遍历图片的像素
*/
int hitCount = 0;
for (int i = minx; i < width-1; i++)
for (int j = miny; j < height; j++) {
int pixel = bi.getRGB(i, j);
int pixelNext = bi.getRGB(i + 1, j);
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
if(rgb[0] > 105){//白色
bi.setRGB(i, j, 0xffffff);
}else if(rgb[0] > 106){
bi.setRGB(i, j, 0x555555);;
}else if(rgb[1] > 75){
bi.setRGB(i, j, 0x000000);
}else if(rgb[2] > 0){
bi.setRGB(i, j, 0x000000);
}else{//黑色
bi.setRGB(i, j, 0x000000);
}
}
return bi;
}
如果你觉得这篇内容对你挺有启发请点赞+关注
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?