如何在使用前端javascript发送到DALL E API之前验证图像

thtygnil  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(157)

我尝试在将图像发送到DALL E API之前验证图像。API拒绝了我需要验证的某些图像属性:
1.档桉类型
1.图像尺寸
1.档桉大小
1.图像是否有alpha通道
做这件事的最好方法是什么?

s8vozzvw

s8vozzvw1#

这是一个适合我的解决方案,尽管我会猜测有更有效的方法来完成它:

验证项目1-3:

// Takes an imageBase64 url (we create locally, within javascript, from a file) and checks the dimensions once rendered.
function checkImageDims(imageBase64: string) {
  const img = new Image();
  img.src = imageBase64;
  const promise = new Promise<string | null>((resolve, reject) => {
    img.onload = () => {
      const { width, height } = img;
      if (height !== width) {
        resolve(
          `Image needs to be square. Current dimensions are ${width}x${height}`
        );
      } else {
        resolve(null);
      }
      img.onerror = reject;
    };
  });
  return promise;
}

// I am using AWS Amplify with S3. This gets the URL to the image:
  const getS3Url = await Storage.get(`myFolder/${s3ObjectName}`);
// Once we have the URL
  const fetched = await fetch(getS3Url);
  const blobbed = await fetched.blob();
  const imageBase64 = URL.createObjectURL(blobbed);
  const dimensionsError = await checkImageDims(imageBase64);
  if (dimensionsError) return dimensionsError;

  console.log({
    size: blobbed.size,
    type: blobbed.type,
  });

验证项目4(alpha)

// Checks image for alpha channel (transparency) https://stackoverflow.com/a/41302302/11664580
function checkForAlphaChannel(buffer: ArrayBuffer) {
  const view = new DataView(buffer);
  // is a PNG?
  if (view.getUint32(0) === 0x89504e47 && view.getUint32(4) === 0x0d0a1a0a) {
    // We know format field exists in the IHDR chunk. The chunk exists at
    // offset 8 +8 bytes (size, name) +8 (depth) & +9 (type)
    const type = view.getUint8(8 + 8 + 9);
    return type === 4 || type === 6; // grayscale + alpha or RGB + alpha
  }
  return false;
}

  const arrayBuffer = await blobbed.arrayBuffer();
  const checkAlpha = checkForAlphaChannel(arrayBuffer);
  console.log({checkAlpha})

α确认的信用https://stackoverflow.com/a/41302302/11664580

相关问题