Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

2.4 KB
Raw Blame
import { Buffer } from 'buffer.js';

import { resolveMimeTypeFromBytes } from './imageMimeType';
import { readBlobWithLimit } from './readBlobWithLimit';
import { ssrfFetch } from './ssrfFetch';

export { readBlobWithLimit } from './readBlobWithLimit';

export const imageToBase64 = ({
  size,
  img,
  type = 'image/webp',
}: {
  img: HTMLImageElement;
  size: number;
  type?: string;
}) => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
  let startX = 0;
  let startY = 0;

  if (img.width > img.height) {
    startX = (img.width - img.height) / 2;
  } else {
    startY = (img.height - img.width) / 2;
  }

  canvas.width = size;
  canvas.height = size;

  ctx.drawImage(
    img,
    startX,
    startY,
    Math.min(img.width, img.height),
    Math.min(img.width, img.height),
    0,
    0,
    size,
    size,
  );

  return canvas.toDataURL(type);
};

export interface ImageUrlToBase64Options {
  /** Abort the download once the response exceeds this many bytes. */
  maxBytes?: number;
  /** Cancels the download, e.g. `AbortSignal.timeout(...)`. */
  signal?: AbortSignal;
}

/**
 * Convert image URL to base64
 * Uses SSRF-safe fetch on server-side to prevent SSRF attacks
 */
export const imageUrlToBase64 = async (
  imageUrl: string,
  options: ImageUrlToBase64Options = {},
): Promise<{ base64: string; mimeType: string }> => {
  try {
    const isServer = typeof window === 'undefined';

    const init = options.signal ? { signal: options.signal } : undefined;
    // Also cap the stream inside ssrfSafeFetch. It truncates silently, so allow one extra
    // byte for readBlobWithLimit to detect the overflow and reject.
    const res = await ssrfFetch(
      imageUrl,
      init,
      options.maxBytes ? { maxContentLength: options.maxBytes + 1 } : undefined,
    );

    const blob = options.maxBytes
      ? await readBlobWithLimit(res, options.maxBytes)
      : await res.blob();
    const arrayBuffer = await blob.arrayBuffer();
    const mimeType = await resolveMimeTypeFromBytes(blob.type, arrayBuffer);

    // Client-side uses btoa, server-side uses Buffer
    const base64 = isServer
      ? Buffer.from(arrayBuffer).toString('base64')
      : btoa(
          new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), ''),
        );

    return { base64, mimeType };
  } catch (error) {
    console.error('Error converting image to base64:', error);
    throw error;
  }
};