int w = img.getWidth(), h = img.getHeight(); // 创建新的字符图片画板 BufferedImage gray = new BufferedImage(w, h, img.getType()); Graphics2D g2d = gray.createGraphics(); g2d.setColor(null); g2d.fillRect(0, 0, w, h);
Font font = new Font("宋体", Font.BOLD, 1); g2d.setFont(font); for (int x = 0; x < w; x ++) { for (int y = 0; y < h; y ++) { g2d.setColor(ColorUtil.int2color(img.getRGB(x, y))); g2d.drawString("灰", x, y); } } g2d.dispose(); System.out.printf("渲染完成"); }
publicstatic Color int2color(int color){ int a = (0xff000000 & color) >>> 24; int r = (0x00ff0000 & color) >> 16; int g = (0x0000ff00 & color) >> 8; int b = (0x000000ff & color); returnnew Color(r, g, b, a); }
/** * 求取多个颜色的平均值 * * @return */ Color getAverage(BufferedImage image, int x, int y, int w, int h){ int red = 0; int green = 0; int blue = 0;
int size = 0; for (int i = y; (i < h + y) && (i < image.getHeight()); i++) { for (int j = x; (j < w + x) && (j < image.getWidth()); j++) { int color = image.getRGB(j, i); red += ((color & 0xff0000) >> 16); green += ((color & 0xff00) >> 8); blue += (color & 0x0000ff); ++size; } }
red = Math.round(red / (float) size); green = Math.round(green / (float) size); blue = Math.round(blue / (float) size); returnnew Color(red, green, blue); }
int w = img.getWidth(), h = img.getHeight(); // 创建新的灰度图片画板 BufferedImage gray = new BufferedImage(w, h, img.getType()); Graphics2D g2d = gray.createGraphics(); g2d.setColor(null); g2d.fillRect(0, 0, w, h);
int size = 12; Font font = new Font("宋体", Font.BOLD, size); g2d.setFont(font); for (int x = 0; x < w; x += size) { for (int y = 0; y < h; y += size) { Color avgColor = getAverage(img, x, y, size, size); g2d.setColor(avgColor); g2d.drawString("灰", x, y); } } g2d.dispose(); System.out.printf("渲染完成"); }