java实现将图片转换成ascii字符文本图像

基本原理

实现原理比较简单,计算图像中像素的灰度值,使用一些ascii字符,如"@#&$%*o!;.",粗略代表几个梯度的灰度值,根据灰度值计算需要填充的ASCII字符,假设计算得到的灰度值为gray,ASCII字符数组为someAscii,填充的ASCII字符Character=someAscii[someAscii.length * gray / 255]。

代码

如果填充每一个像素位ASCII字符,最后得到的ASCII字符文本太大,所以做了一定的压缩处理(每次计算ASCII字符后跳过一定的像素数)

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class AsciiImageCreator {
    public static void create(File srcImgFile, File destAsciiImgFile) {
        final String base = "@#&$%*o!;.";
        String result = "";
        try {
            BufferedImage bufferedImage = ImageIO.read(srcImgFile);
            for (int i = 0; i < bufferedImage.getHeight(); i += 32) {
                for (int j = 0; j < bufferedImage.getWidth(); j += 8) {
                    int pixel = bufferedImage.getRGB(j, i); // 下面三行代码将一个数字转换为RGB数字
                    int red = (pixel & 0xff0000) >> 16;
                    int green = (pixel & 0xff00) >> 8;
                    int blue = (pixel & 0xff);
                    float gray = 0.299f * red + 0.578f * green + 0.114f * blue;
                    int index = Math.round(gray * (base.length() + 1) / 255);
                    result += index >= base.length() ? " " : String.valueOf(base.charAt(index));
                }
                result += "\r\n";
            }
            FileWriter fileWriter = new FileWriter(destAsciiImgFile);
            fileWriter.write(result);
            fileWriter.flush();
            fileWriter.close();
//            System.out.print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void create(String srcImgFile, String destAsciiImgFile) {
        create(new File(srcImgFile),new File(destAsciiImgFile));
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值