简体   繁体   中英

How to get image dimensions on Cloudflare Workers?

I'm trying to create a Cloudflare Worker that receives an image URL and return width and height . But I receive the message ReferenceError: Image is not defined for new Image() . Is there a workaround to make the code below work?

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  let imageUrl = new URL(request.url).searchParams.get('imageUrl')

  let response = await fetch(imageUrl)
  let blob = await response.blob()

  let image = new Image() // <------ ReferenceError: Image is not defined
  return new Promise((resolve, reject) => {
    image.onload = function() {
      resolve(new Response(JSON.stringify({
        width: image.width,
        height: image.height
      }), {
        headers: {
          'content-type': 'application/json'
        }
      }))
    }
    image.onerror = reject
    image.src = URL.createObjectURL(blob)
  })
}

It seems other functions for images have a similar problem. Example: ReferenceError: createImageBitmap is not defined . So any possible solution would be great.

Image are only available in the browse. If you want to get the width and height of an image in node.js try this

const http = require('http');
const fs = require('fs');
const gm = require('gm');

async function handleRequest() {
    const filename = "image.png"
    const fileURL  = "https://any-page.dom/"+filename
    const file = fs.createWriteStream(filename);

    return new Promise((resolve, reject) => {
        const request = http.get(fileURL, function(response) {
            response.pipe(file);
            // after download completed close filestream
            file.on("finish", () => {
                console.log("Download Completed");
                file.close();
                gm(filename)
                 .size(function (err, size) {
                     if (!err) {
                         console.log('width = ' + size.width);
                         console.log('height = ' + size.height);
                         resolve(new Response(JSON.stringify({
                            width: size.width,
                            height: size.height
                          }), {
                            headers: {
                              'content-type': 'application/json'
                            }
                          }))
                     } else {
                        reject(err)
                     }
                 });
            });
         });
      })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM