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); }
private BufferedImage parseImg(BufferedImage img){ int w = img.getWidth(), h = img.getHeight(); // 创建新的灰度图片画板 BufferedImage out = new BufferedImage(w, h, img.getType()); Graphics2D g2d = out.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(); return out; }
// 这里是核心的转换逻辑 List<ImmutablePair<BufferedImage, Integer>> frames = new ArrayList<>(); for (int i = 0; i < decoder.getFrameCount(); i++) { BufferedImage img = decoder.getFrame(i); frames.add(ImmutablePair.of(parseImg(img), decoder.getDelay(i))); }
// 下面是保存gif图 File save = new File("/tmp/out2.gif"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GifHelper.saveGif(frames, outputStream); FileOutputStream out = new FileOutputStream(save); out.write(outputStream.toByteArray()); out.flush(); out.close(); System.out.printf("渲染完成"); }