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;

    }

如果你觉得这篇内容对你挺有启发请点赞+关注

posted @ 2022-07-16 13:52  深山藏古客  阅读(147)  评论(0编辑  收藏  举报