Online experience

  • Cssbattle.wuwenzhou.com.cn/index to give it a try, really can see his mighty under how many layer!!!!!!

Demand analysis

  • Turn HTML code into images.
  • Scenarios such as cssbattle compare code, UI detection, or online generation of PDF, PNG, charts, books, etc

Common SolutionsScience and the Internet

The front-end solutions

  • Html2canvas implementation principle use DOM rendering in canvas, and then use canvas to turn the picture, and then save into base64 practice
  • Pros: Easy to practice.
  • Disadvantages: CSS3 support is not good, screenshots need to calculate the width and height for different scenarios, and it is relatively troublesome to upload data and interact with each other. Interface data can be modified, and the uploaded data itself is already pictures rather than codes, so the logic behind cannot be well guaranteed.

The back-end solution

  • Git address: wkhtmltopdf such c++ scheme
  • Advantages: Easy to use python package can encapsulate the call, screenshot effect is good without other conversion
  • Disadvantages: Cumbersome to install in Docker, poor cSS3 support

Other options

  • Google plugins or paid sites and so on
  • Advantages: Easy to use
  • Disadvantages: High complexity of business combination, can only be used in specific scenarios, payment is absolutely impossible

A native way

  • Chorme, using its own ability screenshots
  • Advantage: the highest degree of reduction
  • Disadvantages: The installation is complicated, and the color value of the screenshot needs to be converted

Technology selection

  • Overall consideration or the use of native capabilities, degree of reduction is the first concern

Code implementation

Pyton code

  • Git address :html2image
from html2image import Html2Image
def screenshot(data) :
    Use SRGB color mode compatibility to compare exported image formats in PS
    hti = Html2Image(custom_flags=['--force-color-profile=SRGB'.'--disable-gpu'])
    Parse the request data
    data = request_parse(request)
    htmlCode = data['code']
    # generate random image address
    timestamp = int(time.time())
    randomStr = ' '.join(random.sample('zyxwvutsrqponmlkjihgfedcba'.5)) 
    png =  str(timestamp)+ randomStr + ".png"
    # This is an unfriendly way to have no height in docker's headless type chorme
    htmlTmp= """     {content}   """
    htmlTmp = htmlTmp.format(content=htmlCode)
    You can view other apis in Git
    hti.screenshot(html_str=htmlTmp,save_as=png,size=(400.300))
Copy the code
  • Picture contrast picture operation: OpencV, data comparison: Numpy
  • Ps: Why not use the common types of image comparison methods: mean value, difference value, perceptual hash algorithm, three-histogram algorithm and single channel algorithm, because the current scene is to compare whether two images are consistent rather than similarity, do not need similarity value, but to determine the error
def runIMGCompareFun(para1, para2) :
    img1 = cv2.imread(para1)
    img1 = cv2.resize(img1, (400.300))
    img2 = cv2.imread(para2)
    img2 = cv2.resize(img2, (400.300))
    # Calculate the absolute error by comparing the matrix to the mean
    arr = img1 == img2
    scale = np.average(arr)
    return scale
Copy the code

Build dependencies

pipreqs --encoding=utf-8 --force
Copy the code

Docker container,

#Mirror basedThe FROM python: 3.7
#port
EXPOSE 9567

#Set the code folder working directory /app
WORKDIR /app
#Copy the current code file to the container /app
COPY . /app

#Timing is importantRUN echo "Acquire::Check-Valid-Until \"false\"; \nAcquire::Check-Date \"false\";" | cat > /etc/apt/apt.conf.d/10no--check-valid-until#Mirror Source Settings
RUN sed -i 's|security.debian.org/debian-security|mirrors.ustc.edu.cn/debian-security|g' /etc/apt/sources.list
RUN sed -i 's#http://deb.debian.org#https://mirrors.163.com#g' /etc/apt/sources.list
#Download the dependentRUN apt-get clean RUN apt-get update -y && apt-get install -y icc-profiles-free RUN apt-get update -y && apt-get install  -y chromium#Headless browser Settings are important
RUN echo 'export CHROMIUM_FLAGS="$CHROMIUM_FLAGS --no-sandbox --disable-gpu"' >> /etc/chromium.d/default-flags
# MOTD
RUN echo " \n =============HTML2IMAGE============= \n Welcome to the html2image CLI container ! \n Type html2image -h for help :)" >> /etc/motd
RUN echo "clear" >> /root/.bashrc
RUN echo "cat /etc/motd" >> /root/.bashrc

#Setting Python static
RUN  pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
#Install the required packages
RUN pip install -r requirements.txt
  
# Run app.py when the container launches
CMD ["python", "run.py"]
Copy the code

conclusion

  • Why Python? Image manipulation and subsequent AI extensions are the most important reasons for choosing Pyhon, scenality and longevity.

  • Python deployment is really cumbersome, with a lot of environment dependencies.

  • The consistency between the local development and the docker container is very important. The local code is good, but the code inside the container will not work properly. The biggest insight of this development is that the docker container can not work properly.

  • Container deployment and upgrade did bring me great convenience this time, script writing process, build docker, release Docker, remote use docker-Watchtower monitoring container changes update restart is really cool.

  • The motherland mother happy birthday, everyone happy holidays!!