图片转换为字符图

2018-09-27  本文已影响241人  sunxiaohang

普通图片转换为ASCII码灰度图片

生在一个表情包横行的年代,没有一打表情包撑场面都不好意思玩社交软件。作为一个集万千diao si气质于一身的程序猿,表情包自然也要玩出玩出花样。下面先看看结果吧。(原图网上一大堆)

1538037045397.png image.png

不论是文字还是像素点,转换效果还是可以的,很清晰。输出是字符集合,感兴趣的小伙伴可以做一个输出流然后截图保存函数。

转换方法

ASSIC编码以复杂度由高到低排序,注意(白色是0xFF,转化出来的灰度值最高)

final static String regularString="@#$&%*!^;,.";

获取图片自身大小

int imageWidth=bufferedImage.getWidth();
int imageHeight=bufferedImage.getHeight();

获取图片RGB然后分别取出RGB值

int orientRGB=bufferedImage.getRGB(coordinateY,coordinateX);
int componentR=(orientRGB>>16)&0xff;
int componentG=(orientRGB>>8)&0xff;
int componentB=orientRGB&0xff;

根据权重求灰度值

int pixelDegree= (int) (componentR*0.3+componentG*0.59+componentB*0.11);

测试文件

BufferedImage bufferedImage= ImageIO.read(imageFile);
convertImageToASSIC(bufferedImage);

完整代码
任务完成,总体代码很简单,哈哈,皮一下很开心系列

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class Main {
    final static String regularString="@#$&%*!^;,.";
    public static void convertImageToASSIC(BufferedImage bufferedImage){
        int imageWidth=bufferedImage.getWidth();
        int imageHeight=bufferedImage.getHeight();
        for(int coordinateX=0;coordinateX<imageHeight;coordinateX+=10){
            for(int coordinateY=0;coordinateY<imageWidth;coordinateY+=6){
                int orientRGB=bufferedImage.getRGB(coordinateY,coordinateX);
                int componentR=(orientRGB>>16)&0xff;
                int componentG=(orientRGB>>8)&0xff;
                int componentB=orientRGB&0xff;
                int pixelDegree= (int) (componentR*0.3+componentG*0.59+componentB*0.11);
                System.out.print(regularString.charAt(pixelDegree/24));
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        File imageFile=new File("resource/face.jpg");
        System.out.println(imageFile.getAbsoluteFile());
        try {
            BufferedImage bufferedImage= ImageIO.read(imageFile);
            convertImageToASSIC(bufferedImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读