. net core using skiasarp text image generation method tutorial (based on docker release)

Time:2020-2-2

1、 Problem background

At present, Microsoft does not integrate the image processing library under. Net core. Under. Net framework, we are used to using system.drawing class library to do simple image processing. Under. Net core, I am so confused that I can only Baidu + Google to see if there is any solution. Well, there are many online materials. Under. Net core, there are some open source libraries for image processing. I use them now One of them: skiasarp, introduce that everyone has searched online anyway. Next, use this library to realize a small function of text head portrait. Let’s have a look at the detailed introduction.

2、 Simple design requirements

  • The input name must be parsed (Chinese, English)
  • Picture background color will change randomly
  • The words should be centered (nonsense, not centered is not ugly)

3、 Specific implementation

1. Resolve name information

private String ResolveName(String imageText)
  {
   Imagetext. Replace ("?", "". Replace (":", "). Replace ("? ","). Replace ("*", "). Replace (" < ","). Replace (">", "). Replace (@" / ","). Replace (@ "\", "); // remove information not supported by path
   Imagetext = imagetext. Trim (''); // remove the space information
   String temp2 = imagetext. Substring (0, 1); // according to the data of the first digit, judge whether to follow the English rule or the Chinese rule. If neither is the case, the first two digits will be taken
   if (RegexLib.IsChineseCharacter(temp2))
   {
    //UserName = UserName.Trim(' ');
    if (imageText.Length > 2 & imageText.Length <= 3)
    {
     imageText = imageText.Substring(1, 2);
    }
    else if (imageText.Length >= 3)
    {
     imageText = imageText.Substring(imageText.Length - 2, 2);
    }
   }
   else if (RegexLib.IsEnglishCharacter(temp2))
   {
    String[] temp1 = imageText.Split(' ');
    if (temp1.Length == 2)
    {
     imageText = (temp1[0].Substring(0, 1) + temp1[1].Substring(0, 1)).ToUpper();
    }
    else
    {
     if (imageText.Length > 2)
     {
      imageText = imageText.Substring(0, 2).ToUpper();
     }
    }
   }
   else
   {
    if (imageText.Length > 2)
    {
     imageText = imageText.Substring(0, 2);
    }
   }
   imageName = imageText;
   return imageName;
  }

2. Generate pictures from text

public byte[] Create()
  {
   String name = imageName + ".jpg";
   SKBitmap bmp = new SKBitmap(128, 128);
   String str = imageName;

   using (SKCanvas canvas = new SKCanvas(bmp))
   {
    Random r = new Random();
    int num = r.Next(0, 9);
    Canvas. Drawcolor (colors [num]); // colors is the background color set of the picture. The code will not be pasted here. Find one randomly
    using (SKPaint sKPaint = new SKPaint())
    {
     Skpaint. Color = skcolors. White; // font color
     Skpaint. Textsize = 39; // font size
     Skpaint. Isantilias = true; // enable anti aliasing
     Skpaint. Typeface = skiasarp. Sktypeface. Fromfamilyname ("Microsoft YaHei", sktypefacestyle. BOLD); // font
     SKRect size = new SKRect();
     Skpaint. Measuretext (STR, ref size); // calculate text width and height
     float temp = (128 - size.Size.Width) / 2;
     float temp1 = (128 - size.Size.Height) / 2;
     Canvas. DrawText (STR, temp, temp1 - size. Top, skpaint); // draw text
    }
    //Save as picture file
    using (SKImage img = SKImage.FromBitmap(bmp))
    {
     using (SKData p = img.Encode(SKEncodedImageFormat.Jpeg, 100))
     {
      return p.ToArray();
      //using (var stream = File.Create(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "photoImage", name)))
      //{
      // stream.Write(p.ToArray(), 0, p.ToArray().Length);
      // return stream;
      //}
     }
    }
   }
  }

I just get the byte [] array here. If I need to convert it to stream or save it as a file, I can find all the methods. I will not put it out,

3、 Docker released pit

Pit 1: it’s OK under IIS, and the docker reports an error

Because the dependency libraries used by skiasarp under windows and Linux are different. If they are deployed in the same way as before, the “the type initializer for ‘skiasarp. Skimageinfo’ thread an exception” will appear in docker. The reason is that skiasarp under Linux depends on libskiasarp.so. If there is no libskiasarp.so in the system, this error will be reported. At present, my simplest operation is Find the file and leave it in the directory of skiasarp, then you can

Pit 2: Chinese font is not recognized

Because there is no Chinese font in docker, so, when you want to output Chinese, you need to bring it with you. As shown in the figure below, the solution is to copy the font into docker

  

The following provides the dockerfile I use. How to use the dockerfile can only be used by you Baidu (PS: the real reason is that I am also a weak chicken in this respect — I’m afraid to mislead you). My environment is CentOS 7.3

#Build our image based on 'Microsoft / dotnet: latest'
FROM microsoft/dotnet:latest

#Copy all files in the project publish folder to the publish folder in the docker container 
COPY . /publish /publish/

#ENV LANG C.UTF-8
#ENV LANGUAGE C.UTF-8
#ENV LC_ALL C.UTF-8
COPY MSYH.TTC /usr/share/fonts/dejavu
COPY MSYHL.TTC /usr/share/fonts/dejavu
COPY MSYHBD.TTC /usr/share/fonts/dejavu

#Change software source to domestic software source
RUN mv /etc/apt/sources.list /etc/apt/sources.list.bak && \
 echo "deb http://mirrors.163.com/debian/ jessie main non-free contrib" >/etc/apt/sources.list && \
 echo "deb http://mirrors.163.com/debian/ jessie-proposed-updates main non-free contrib" >>/etc/apt/sources.list && \
 echo "deb-src http://mirrors.163.com/debian/ jessie main non-free contrib" >>/etc/apt/sources.list && \
 echo "deb-src http://mirrors.163.com/debian/ jessie-proposed-updates main non-free contrib" >>/etc/apt/sources.list
#RUN apt-get update && apt-get install -y libfontconfig1 && apt-get install -y fontconfig
RUN apt-get update && apt-get install -y fontconfig

#Set the working directory to the folder '/ publish', which is the default folder for container startup
WORKDIR /publish

#Set the docker container to expose 5000 ports
EXPOSE 5000

#Use 'dotnet webapplication1. DLL' to run the application

CMD ["dotnet", "WebApplication1.dll"]

The previous picture of success:

  

Last demo address

Four, summary

Docker is a good thing, but I’m too weak. I need to spend more time to learn. Programmers may have to live and learn!

PS: I found out the above by myself. If you have a better way to realize it, welcome to discuss. Thank you for watching

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.