有没有一种方法可以轻松检查图片网址是否有效?

时间:2019-04-27 11:41:55

标签: javascript image

我正在尝试编写一个函数,该函数检查图像URL是否为实际图像,如果是,它将返回true,否则将返回false,

类似的东西:

checkImage(imageURL){
  if imageURL.isReal{
    return true
 }
 return false
}

我找到了很多答案,但是它们并没有真正用作布尔函数

3 个答案:

答案 0 :(得分:3)

最优雅的解决方案是使用 XMLHttpRequest 并检查响应代码。 如果它是 200 ,则图像存在;如果图像有所不同,则很可能图片-或更确切地说是网址不存在。 这是一个示例:

function checkImage(url) {
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.send();
  request.onload = function() {
    status = request.status;
    if (request.status == 200) //if(statusText == OK)
    {
      console.log("image exists");
    } else {
      console.log("image doesn't exist");
    }
  }
}
checkImage("https://picsum.photos/200/300");

嗯,正如我所说的,这是一种更通用的方法。 如果要确保它实际上是图像,则可以利用Image对象的 onerror onload 事件。

function checkImage(url) {
  var image = new Image();
  image.onload = function() {
    if (this.width > 0) {
      console.log("image exists");
    }
  }
  image.onerror = function() {
    console.log("image doesn't exist");
  }
  image.src = url;
}
checkImage("https://picsum.photos/200/300");

答案 1 :(得分:2)

您可以使用XMLHttpRequest的 getResponseHeader 来检查请求的成功返回内容的mime类型。实际上,仅根据请求的http成功响应代码,您就无法知道响应的内容。

  

XMLHttpRequest方法getResponseHeader()返回字符串   包含特定标题值的文本。如果有   具有相同名称的多个响应标头,则它们的值为   作为单个串联字符串返回,其中每个值是   用一对逗号和空格将前一个分隔开。的   getResponseHeader()方法以UTF字节序列的形式返回该值。


  

在此示例中,创建并发送了一个请求,并准备状态更改   建立处理程序以查找readyState来指示   标头已收到;在这种情况下,   获取Content-Type标头。如果不是所需的Content-Type   值,则通过调用abort()取消XMLHttpRequest。

#define GLEW_STATIC
#define _USE_MATH_DEFINES
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <gl/gl.h>
#include <math.h>
#include <iostream>

const int ARC_VERTEX_COUNT = 100;

// Don't use global variables at home, kids!
GLFWwindow* window;
GLuint shader;
GLint shaderLoc_pos;
GLuint vbo_circle;
GLuint vbo_arc;

float normalizeAngleToSmallestPositive(float angle) {
    while (angle < 0.0) { angle += M_PI*2; }
    while (angle >= M_PI*2) { angle -= M_PI*2; }
    return angle;
}

bool startApp() {
    if (!glfwInit()) {
        return false;
    }
    window = glfwCreateWindow(500, 500, "Hello World", NULL, NULL);
    if (!window) {
        glfwTerminate();
        return false;
    }
    glfwMakeContextCurrent(window);
    glewInit();
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glLineWidth(10.0);
    return true;
}

void stopApp() {
    glfwTerminate();
}

void createShader() {
    const char* vsSrc =
        "#version 330 core\n"
        "in vec2 pos; void main() { gl_Position = vec4(pos, 0.0, 1.0); }";
    const char* fsSrc =
        "#version 330 core\n"
        "out vec4 color; void main() { color = vec4(1.0,1.0,1.0,0.5); }";

    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, &vsSrc, nullptr);
    glCompileShader(vs);

    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1, &fsSrc, nullptr);
    glCompileShader(fs);

    shader = glCreateProgram();
    glAttachShader(shader, vs);
    glAttachShader(shader, fs);
    glLinkProgram(shader);

    shaderLoc_pos = glGetAttribLocation(shader, "pos");
}

// Create an arc between two given angles, based on the circle described by the given radius and
// center point
GLuint createArc(float angle1, float angle2, float radius, float x, float y, float useBiggerArc) {
    // Prepare angles
    angle1 = normalizeAngleToSmallestPositive(angle1);
    angle2 = normalizeAngleToSmallestPositive(angle2);
    if (angle1 > angle2) {
        float buffer = angle1;
        angle1 = angle2;
        angle2 = buffer;
    }
    if (useBiggerArc != angle2-angle1 > M_PI) {
        angle1 += M_PI*2;
    }

    // Create opengl geometry
    GLfloat pos[ARC_VERTEX_COUNT * 2];
    for (int i = 0; i < ARC_VERTEX_COUNT; i++) {
        pos[i*2] = sin((float)i / (ARC_VERTEX_COUNT-1) * (angle2 - angle1) + angle1) * radius + x;
        pos[i*2+1] = cos((float)i / (ARC_VERTEX_COUNT-1) * (angle2 - angle1) + angle1) * radius + y;
    }
    GLuint result;
    glGenBuffers(1, &result);
    glBindBuffer(GL_ARRAY_BUFFER, result);
    glBufferData(GL_ARRAY_BUFFER, sizeof(pos), pos, GL_STATIC_DRAW);
    return result;
}

GLuint createCircle(float radius, float x, float y) {
    return createArc(M_PI*0, M_PI*2, radius, x, y, true);
}

// Create an arc between two given points that is based on a circle with the given radius.
GLuint createArc(
    float x1, float y1, float x2, float y2, float radius, bool arcDirection, bool useBiggerArc)
{
    // distance between points
    float distance = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
    // halfway point
    float xAverage = (x1+x2)/2.0;
    float yAverage = (y1+y2)/2.0;
    // circle center
    float xCenter = sqrt(radius*radius - distance*distance/4.0) * (y1-y2) / distance;
    float yCenter = sqrt(radius*radius - distance*distance/4.0) * (x2-x1) / distance;
    xCenter = xAverage + (arcDirection ? xCenter : -xCenter);
    yCenter = yAverage + (arcDirection ? yCenter : -yCenter);
    // angles
    float angle1 = atan2(x1-xCenter, y1-yCenter);
    float angle2 = atan2(x2-xCenter, y2-yCenter);
    // create the arc
    return createArc(angle1, angle2, radius, xCenter, yCenter, useBiggerArc);
}

void runMainLoop() {
    while (!glfwWindowShouldClose(window)) {
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader);
        glEnableVertexAttribArray(shaderLoc_pos);

        glBindBuffer(GL_ARRAY_BUFFER, vbo_circle);
        glVertexAttribPointer(shaderLoc_pos, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
        glDrawArrays(GL_LINE_STRIP, 0, ARC_VERTEX_COUNT);

        glBindBuffer(GL_ARRAY_BUFFER, vbo_arc);
        glVertexAttribPointer(shaderLoc_pos, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
        glDrawArrays(GL_LINE_STRIP, 0, ARC_VERTEX_COUNT);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
}

int main(void) {
    if (startApp())
    {
        createShader();
        vbo_circle = createCircle(0.75, 0.0, 0.0);
        vbo_arc = createArc(0.0, 0.75, 0.75, 0.0, 0.75, false, false);

        runMainLoop();
        stopApp();
        return 0;
    }
    else
    {
        return -1;
    }
}

祝一切顺利。

答案 2 :(得分:0)

您可以使用 fetch API。 XHR 的现代变体。

很喜欢

async function checkImage(url){
     
     const res = await fetch(url);
     const buff = await res.blob();
    
     return buff.type.startsWith('image/')

}

这样

checkImage('https://example.com/notAnImage.txt') // false
checkImage('https://example.com/image.png') // true