Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

javascript - Unable to show .png extension images

I have this whole snippet over here which essentially, makes a page to domain.com/api/canvas/fake-captcha, but not domain.com/api/canvas/fake-captcha.png / jpg / etc... and I am not sure how to do so. This is supposed to display an Image, that's my issue.

module.exports = {
  name: "/api/canvas/fake-captcha",
  run: async (req, res) => {
    // REQUIREMENTS
    const { createCanvas, loadImage, registerFont } = require('canvas');
    const { CaptchaGenerator } = require("captcha-canvas");

    // CREATE CANVAS
    const canvas = createCanvas(450, 150)
    const ctx = canvas.getContext('2d')

    // VALIDATORS
    const isImageURL = require('image-url-validator');
    const isHexcolor = require('is-hexcolor')
    // FONT
    registerFont("fonts/Montserrat-Bold.ttf", { family: "Montserrat" });

    let randomOpacity = Math.floor((Math.random() * 9) + 1);

    function randomCaptcha(length) {
      var result = '';
      var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      var charactersLength = characters.length;
      for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
      }
      return result;
    }

    let captchaCustom = req.query.captcha || randomCaptcha(5);
    let traceCol = req.query.trace_color || "55FFFF";
    let captchaCol = req.query.captcha_color || "55FFFF";

let traceColorC = await isHexcolor('#' + traceCol);

    const captcha = new CaptchaGenerator()
      .setDimension(150, 450)
      .setCaptcha({ text: captchaCustom, size: 60, color: "#" + captchaCol })
      .setDecoy({ opacity: 0. + randomOpacity })
      .setTrace({ color: "#" + traceCol });
    const buffer = captcha.generateSync();

    res.writeHead(200, {
      'Content-Type': 'image/png',
      'Content-Length': captcha.generateSync().length
    });
    res.end(captcha.generateSync());
  }
}
question from:https://stackoverflow.com/questions/65938732/unable-to-show-png-extension-images

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...