Golang实现文字转字符画

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ikevin/article/details/71122592

Golang实现文字转字符画

简单说下原理:使用文字创建位图,然后根据位图计算每个像素点的灰度,根据灰度使用不同的字符将所有像素拼接即可.
1.相关使用的包

  import (

      "github.com/golang/freetype"
      "fmt"
      "image"
      "strconv"
      //"image/color"
      "image/png"
      "io/ioutil"
      "log"
      "os"

  )

2.根据文字创建图像

  func createImage(textName string) {

      imgfile, _ := os.Create(textName+".png")
      defer imgfile.Close()
      //创建位图,坐标x,y,长宽x,y
      img := image.NewNRGBA(image.Rect(0, 0, 100,40))
      /*
      // 画背景,这里可根据喜好画出背景颜色
      for y := 0; y < dy; y++ {
          for x := 0; x < dx; x++ {
              //设置某个点的颜色,依次是 RGBA
              img.Set(x, y, color.RGBA{uint8(x), uint8(y), 0, 255})
          }
      }
     */
      //读字体数据
      fontBytes, err := ioutil.ReadFile("consola.TTF")
      if err != nil {
          log.Println(err)
          return
      }

      font, err := freetype.ParseFont(fontBytes)
      if err != nil {
          log.Println(err)
          return
      }

      c := freetype.NewContext()
      c.SetDPI(72)
      c.SetFont(font)
      c.SetFontSize(40)
      c.SetClip(img.Bounds())
      c.SetDst(img)
      c.SetSrc(image.White)
      //设置字体显示位置
      pt := freetype.Pt(5, 20+int(c.PointToFixed(40)>>8))
      _, err = c.DrawString(textName, pt)
      if err != nil {
          log.Println(err)
          return
      }
      //保存图像到文件
      err = png.Encode(imgfile, img)
      if err != nil {
          log.Fatal(err)
      }

  }

3.根据图像输出字符画

    func drawAscii(){
    //灰度替换字符
       base := "@#&$%*o!;."
       file1, _ := os.Open("TASS.png") //图像名称
       image1, _ := png.Decode(file1)
       bounds:=image1.Bounds()//获取图像的边界信息
       logo:=""//存储最终的字符画string
       for y:=0;y<bounds.Dy();y+=2{
           for x:=0;x<bounds.Dx();x++{
               pixel:=image1.At(x, y)//获取像素点
               r, g, b, _ := pixel.RGBA()//获取像素点的rgb
               r=r&0xFF
               g=g&0xFF
               b=b&0xFF
               //灰度计算
               gray := 0.299 * float64(r) + 0.578 * float64(g) + 0.114 * float64(b)
               temp:=fmt.Sprintf("%.0f",gray*float64(len(base)+1)/255)
               index,_:=strconv.Atoi(temp)
               //根据灰度索引字符并保存
               if index>=len(base) {
                    logo+=" "
               }else{
                    logo+=string(base[index])
               }

           }
           logo+="\r\n"
       }
       file1.Close()
       //输出字符画
       log.Printf("\033[31;1m%s , %d",logo,len(logo))
   }

4.效果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/ikevin/article/details/71122592