'How to convert SvelteKit fetch response to a buffer?

I have a simple node script to fetch tif image, use sharp to convert the image to jpeg and generate data:image/jpeg;base64 src for browser. The reason is to enable tiff image in browsers that do not support tif/tiff images.

In node this works great.

import sharp from "sharp";
import fetch from "node-fetch";

let link =
  "https://people.math.sc.edu/Burkardt/data/tif/at3_1m4_01.tif";

// fetch tif image and save it as a buffer
async function fetchTifBuffer(link) {
  const tifImg = await fetch(link);
  const buffer = await tifImg.buffer();
  return buffer;
}

// convert to png image save to buffer and save as base64
async function tifToPngToBase64(link) {
  let inputImgBuffer = await fetchTifBuffer(link);
  const buff = await sharp(inputImgBuffer).toFormat("jpeg").toBuffer();
  let base64data = buff.toString("base64");
  let imgsrc = "data:image/jpeg;base64," + base64data.toString("base64");
  console.log(imgsrc);
  // use in browser  <img src="data:image/jpeg;base64,/9j/2wBDAAYEBQYFBAY ...==" alt="image" />
}

tifToPngToBase64(link);

I would like to implement this in SvelteKit. But I have no idea how to get buffer from SvelteKit fetch response. Any ideas?



Solution 1:[1]

Ok, so I figured it out by myself. SvelteKit fetch response has an arrayBuffer, so all that is needed is to convert the arraybuffer to the buffer.

This is the relevant SvelteKit endpoint:

// img.js
import sharp from "sharp";

export const get = async () => {
  const res = await fetch(
    "https://people.math.sc.edu/Burkardt/data/tif/at3_1m4_01.tif"
  );
  const abuffer = await res.arrayBuffer();

  const buffer = Buffer.from(new Uint8Array(abuffer));
  const buff = await sharp(buffer).toFormat("jpeg").toBuffer();
  let base64data = buff.toString("base64");

  let src = `data:image/jpeg;base64,${base64data.toString("base64")}`;
  let img = `<img style='display:block; width:100px;height:100px;' id='base64image'
       src='${src}' />`;
  return {
    body: {
      img,
    },
  };
};

and this is the SvelteKit component which uses the endpont:

// img.svelte
<script>
  export let img;
</script>

{@html img}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1