seeway

导航

Java实现把图片转成字符画

1,先看效果图:

2,建议图片尺寸不要太大,长宽不要超过200px效果最佳

3,代码如下:

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

public class ImageToStr {

    public static void createAsciiPic(final String path) {
        //final String base = "@#&$%*o!;.";// 字符串由复杂到简单
        final String base = "KSPksp;.";
        try {
            final BufferedImage image = ImageIO.read(new File(path));
            System.out.println("W:"+image.getWidth()+" H:"+image.getHeight());
            for (int y = 0; y < image.getHeight(); y += 2) {
                for (int x = 0; x < image.getWidth(); x++) {
                    final int pixel = image.getRGB(x, y);
                    final int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;
                    final float gray = 0.299f * r + 0.578f * g + 0.114f * b;
                    final int index = Math.round(gray * (base.length() + 1) / 255);
                    System.out.print(index >= base.length() ? " " : String.valueOf(base.charAt(index)));
                }
                System.out.println();
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args []){
        ImageToStr.createAsciiPic("C:\\Users\\Administrator\\Desktop\\字符画\\ksp1.jpg");
    }


}

4,注:final String base = "@#&$%*o!;.";表示组成字符画字符元素

 

posted on 2018-10-24 16:35  seeway  阅读(1233)  评论(0编辑  收藏  举报