通过MATLAB将位图转化为ASCII图形

ASCII图形是一种用字符代替图形的方法,它使用ASCII字符依照图片进行拼凑得到所需的形状。利用MATLAB可以实现将位图转换为ASCII图形,随后可以在HTML文件中使用等宽字体很好地显示结果。

该MATLAB函数接受3个输入,分别为图片的文件路径filepath、转换方式style与输出分辨率OutPic_lateral_res。输出分辨率默认128字符,变量alpha指定了背景图片的透明度。程序通过文件路径读取图片后利用imresize函数将图片缩放到指定的输出分辨率,随后将rgb图像转换为灰度图。最后按FillChar的明暗顺序将灰度图像转换为ASCII字符,并输出为ASCII Art.txt。源代码如下。

function img2ascii(filepath,style,OutPic_lateral_res)

if(~exist('OutPic_lateral_res','var'))
    OutPic_lateral_res=128;
end
alpha=0.5;
OriPic=imread(filepath);
scale=OutPic_lateral_res/size(OriPic,2);
OriPic=imresize(OriPic,scale,'nearest');

GraPic=rgb2gray(OriPic);
if any(GraPic>1)
    GraPic=double(GraPic)/255;
end
if strcmp(style,'gray')
    OutPic=imresize(GraPic,1/scale,'nearest');
    Alpha=alpha*ones(size(OutPic,1:2));
    imwrite(OutPic,'ASCII Art.png','Alpha',Alpha);
elseif strcmp(style,'color')
    OutPic=imresize(OriPic,1/scale,'nearest');
    Alpha=alpha*ones(size(OutPic,1:2));
    imwrite(OutPic,'ASCII Art.png','Alpha',Alpha);
elseif strcmp(style,'classic')
    OutPic=uint8([]);
else
    error("Wrong style input");
end
FillChar='$@WME#8}]=+-;,,..  ';
FillChar_Len=length(FillChar);
GraPic=floor(GraPic*(FillChar_Len-1))+1;
StrPic=FillChar(GraPic);

filename='ASCII Art.txt';
writematrix(StrPic,filename,'delimiter','tab');

end

若要将ASCII图像利用HTML文件进行展示,可以利用较粗的等宽字体展示。HTML文件如下。

<html>
<head>
  <meta charset="utf-8">
  <title>ASCII Art</title>
  <style>
    @font-face {
      font-family: MonoSquare;
      src: url("https://cdn.jsdelivr.net/gh/ycythu/assets@main/fonts/Topaz/Topaz-8.ttf")
    }
    body{
      margin-left: 0px;
      margin-top: 0px;
      margin-right: 0px;
      margin-bottom: 0px;
    }
    #IMG {
        background-image: url("ASCII Art.png");
        background-repeat: no-repeat;
        background-size: "100% 100%";
    }
    #ASCII {
      font-family: MonoSquare;
      letter-spacing:2.664px;
      white-space: pre;
      line-height: 100%;
      boarder:none;
      float:left;
    }
  </style>
</head>

<body>
<div id="IMG">
  <div id="ASCII">......</div>
</div>
</body>

<script>
window.onload = function(){
  var ASCII = document.getElementById('ASCII');
  var IMG = document.getElementById("IMG");
  IMG.style.width = ASCII.offsetWidth+'px';
  IMG.style.height = ASCII.offsetHeight+'px';
  document.body.offsetWidth = ASCII.offsetWidth+'px';
  document.body.offsetHeight = ASCII.offsetHeight+'px';
  IMG.style.backgroundSize = ASCII.offsetWidth+"px "+ASCII.offsetHeight+"px"
}
</script>
</html>

在函数img2ascii中,参数style决定了背景图片的格式,当style分别被设置为'color','gray','classic'时,在HTML中的显示效果如下图。

输出分辨率OutPic_lateral_res的设置会影响ASCII字符画的可辨识度。当style='classic',OutPic_lateral_res分别取192,128,96,64时的输出图片与原图对比如下。