测试
1 public static void create_4bit(File file) throws IOException { 2 3 if (!file.exists()) { 4 System.err.println("文件不存在!" + file.getAbsolutePath()); 5 return; 6 } 7 8 int width = (int) Math.ceil(Math.sqrt(file.length() * 2)); 9 width = width % 2 == 0 ? width : width + 1;//宽度必须为偶数,读取的时候是成对读取的,2个像素为1个字节数据 10 int height = (int) Math.ceil((double) file.length() / (double) (width / 2)); 11 System.out.println(width + " " + height); 12 13 BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 14 FileInputStream fis = new FileInputStream(file); 15 16 byte[] b = new byte[1024]; 17 int s, count = 0, x = 0, y = 0; 18 19 while ((s = fis.read(b)) != -1) { 20 for (int i = 0; i < s; i++) { 21 22 String hex = String.format("%02X", b[i]); 23 Color rgb = ColorTable.HEX_VALUES_4BIT[Integer.parseInt(hex.substring(0, 1), 16)]; 24 buffer.setRGB(x, y, rgb.getRGB()); 25 rgb = ColorTable.HEX_VALUES_4BIT[Integer.parseInt(hex.substring(1, 2), 16)]; 26 buffer.setRGB(x + 1, y, rgb.getRGB()); 27 count++; 28 x += 2; 29 if (count % (width / 2) == 0) { 30 x = 0; 31 y++; 32 } 33 } 34 } 35 System.out.println(y); 36 fis.close(); 37 if (!ImageIO.write(buffer, "png", new File("2.png"))) 38 System.err.println("执行失败!"); 39 }
测试
浙公网安备 33010602011771号