字符动图_轻松一刻:用 Java 生成 ASCII 字符动画(附源码)

原理

原理很简单。一张图片的色彩,基本上由红绿蓝三基色构成。然后我们把对应颜色的像素用ascii字符来替代,这样就可以得到一张ascii字符画了,如果是视频,我们可以将视频读取到缓冲池,然后对视频的每一帧进行如上处理,最后将得到的ascii字符画合成,就得到了ascii动画。

步骤

第一步:我们先将图像转换为灰度图(使用黑色调表示物体,即用黑色为基准色,不同的饱和度的黑色来显示图像),然后让其通过一个阈值滤波器,此时就得到了一个黑白对比图。

第二步:我们可以将其与每个字符对比并计算差值。

第三步:接着,对每个图片块选取最相似的字符,一直进行下去,直到整个图像都转换完成。

第四步:根据需要调整阈值大小来影响对比度,并增强最终的结果。

为了实现这一点,一个非常简单的方法是将红、绿、蓝的值都设置成三种颜色的平均值:红=绿=蓝 =(红+绿+蓝)/ 3

代码实现

public Output convertImage(final BufferedImage source) {   // 每个图块的尺寸   Dimension tileSize = this.characterCache.getCharacterImageSize();   // 四舍五入宽度和高度,所以我们避免部分字符   int outputImageWidth = (source.getWidth() / tileSize.width)         * tileSize.width;   int outputImageHeight = (source.getHeight() / tileSize.height)         * tileSize.height;   //从源图像中提取像素   int[] imagePixels = source.getRGB(0, 0, outputImageWidth,         outputImageHeight, null, 0, outputImageWidth);   // 将像素处理为灰度矩阵   GrayscaleMatrix sourceMatrix = new GrayscaleMatrix(imagePixels,         outputImageWidth, outputImageHeight);   //将矩阵分成小块以便于处理   TiledGrayscaleMatrix tiledMatrix = new TiledGrayscaleMatrix(         sourceMatrix, tileSize.width, tileSize.height);   this.output = initializeOutput(outputImageWidth, outputImageHeight);   //比较每个图块与每个角色,以确定最合适的位置   for (int i = 0; i < tiledMatrix.getTileCount(); i++) {      GrayscaleMatrix tile = tiledMatrix.getTile(i);      float minError = Float.MAX_VALUE;      Entry bestFit = null;      for (Entry charImage : characterCache) {         GrayscaleMatrix charPixels = charImage.getValue();         float error = this.characterFitStrategy.calculateError(               charPixels, tile);         if (error < minError) {            minError = error;            bestFit = charImage;         }      }      int tileX = ArrayUtils.convert1DtoX(i, tiledMatrix.getTilesX());      int tileY = ArrayUtils.convert1DtoY(i, tiledMatrix.getTilesX());      // 复制字符到输出      addCharacterToOutput(bestFit, imagePixels, tileX, tileY,            outputImageWidth);   }   finalizeOutput(imagePixels, outputImageWidth, outputImageHeight);   return this.output;}

最终效果

95ff1c0b332b3dcc2060b5cc1003831e.gif

原图

7dbe9e67fba601cf3fe47518d9aff018.gif

ascii动图

评论或者私信获取源码。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值