GithubHelp home page GithubHelp logo

Comments (4)

lovell avatar lovell commented on May 27, 2024

I cannot reproduce this locally using Bun 1.0.35 via the oven/bun (Debian 11) Docker container.

If you're still having problems, please provide a complete code sample and image that allows someone else to reproduce.

from sharp.

billyadelphia avatar billyadelphia commented on May 27, 2024

I cannot reproduce this locally using Bun 1.0.35 via the oven/bun (Debian 11) Docker container.

If you're still having problems, please provide a complete code sample and image that allows someone else to reproduce.

This is the entire code

Just my small service to remove the background image and then trim it using sharp

import Fastify from "fastify";
import { removeBackground } from "@imgly/background-removal-node";
const fastify = Fastify({
  // logger: true
});
import { Buffer } from "buffer";
import cors from "@fastify/cors";
import axios from "axios";
import { writeFileSync } from "fs";
import { join } from "path";
import { randomBytes } from "crypto";
import imageType from "image-type";
import { fileURLToPath } from "url";
import { dirname } from "path";
import sharp from "sharp";
import fs from "fs";

const __dirname = dirname(fileURLToPath(import.meta.url));

await fastify.register(cors, {
  origin: "*",
});

const downloadImage = async (url: string) => {
  const response = await axios.get(url, { responseType: "arraybuffer" });
  const buffer = Buffer.from(response.data, "binary");

  // Get the image type from the buffer
  const type = await imageType(buffer);
  console.log("type", type);
  // If the image type couldn't be detected, throw an error
  if (!type) {
    throw new Error("Could not detect image type");
  }

  // Generate a random filename with the correct extension
  const filename = randomBytes(16).toString("hex") + "." + type.ext;

  // Full path of the image
  const imagePath = join(__dirname, "backgroundImages", filename);

  // Save the image
  writeFileSync(imagePath, buffer);

  // Return the full path of the image
  return imagePath;
};

// Declare a route
fastify.post("/remove-background", async function handler(request, reply) {
  console.log("search");
  const body = request.body as any;
  const imageUrl = body.imageUrl;
  const imageId = body.imageId;
  console.log("body", body);
  if (!imageUrl && !imageId) {
    console.log("Invalid Request", "if (!imageUrl || !imageId) {");
    return reply.code(400).send("Invalid Request");
  }

  if (!imageUrl.startsWith("http")) {
    console.log("Invalid Request", "if (!imageUrl.startsWith('http')) {");
    return reply.code(400).send("Invalid Request");
  }
  let result: Blob | undefined;
  if (imageUrl) {
    try {
      //download the image, and save it to a file in backgroundImages folder
      const data = await downloadImage(imageUrl);
      console.log("removeBackground(data, {");
      result = await removeBackground(data, {
        debug: true,
        output: { format: "image/png", quality: 1 },
      });

      //remove the image file
      fs.unlinkSync(data);
    } catch (e) {
      console.log("err await removeBackground(imageUrl);", e);
      return reply.code(400).send("Invalid Request");
    }
  }
  console.log("theResultDone");
  if (!result) {
    return reply.code(400).send("Invalid Request");
  }

  const buffer = await result.arrayBuffer();
  let theBase64 = Buffer.from(buffer).toString("base64"); // you can ignore this, it's just the part of the code before I implement sharp
  // console.log("base64Image", theBase64); // This will log the base64 representation of the image
  //convert result to base64 png
  // theBase64 = `data:image/png;base64,${theBase64}`;
  // console.log("theBase64", theBase64);
  console.log("sharpingsharpingsharping");
  const theSharp = await sharp(buffer).trim().toBuffer();
  console.log("theSharp done");
  theBase64 = theSharp.toString("base64");
  theBase64 = `data:image/png;base64,${theBase64}`;

  const data = {
    base64: theBase64,
  };
  // console.log("data", data);
  return reply.code(200).send(data);
});

// Run the server!
try {
  await fastify.listen({ port: 5832 });
  console.log(`server listening on ${fastify.server.address().port}`);
} catch (err) {
  fastify.log.error("ulalafast", err);
  process.exit(1);
}

from sharp.

lovell avatar lovell commented on May 27, 2024

Please can you provide a more minimal code sample that allows someone else to reproduce. For example, please remove all networking code, and please remove the other dependencies such as @imgly/background-removal-node.

Perhaps create a complete, minimal, standalone repo that makes it as simple as possible for someone else to reproduce.

from sharp.

lovell avatar lovell commented on May 27, 2024

I've just spotted that @imgly/background-removal-node depends on an old version of sharp and will not work on Bun.

https://github.com/imgly/background-removal-js/blob/688472762e819747362e3e88d5322a8cdbf8a967/packages/node/package.json#L63

Support for Bun was added in sharp v0.33.0.

from sharp.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.