[英]How to remove black area or black area to transparent png image using javascript?
我過去曾嘗試做類似的事情,但在查看了幾個資源后,我意識到僅使用 Sharp 無法從圖像中刪除背景。 您可能還必須使用另一個 package,例如 Rembg。 你可以這樣做:
// Import the sharp and rembg library for image processing
const { Rembg } = require("rembg-node");
const sharp = require("sharp");
(async () => {
const input = sharp("Path/to/your/image.png"); // Load the input image using Sharp
// Create a new instance of the Rembg class (optional arguments can be provided)
const rembg = new Rembg();
// Apply background removal by calling the remove() method of the Rembg instance
const output = await rembg.remove(input);
await output.toFile("path/to/your/destination.png"); // Save the output image with the background removed
})();
注意:Rembg 不是很流行的 package,所以你需要使用 yarn 來安裝它。
我發現的另一個簡單的解決方案是免費增值 Cloudinary AI 后台刪除服務。 我試了一下,它在刪除背景方面非常一致。 為此,在您的項目中安裝 Cloudinary Node.js SDK 。 通過轉到附加組件>Cloudinary AI 背景刪除並訂閱免費計划來啟用插件。 然后在 Node.js 中運行這個簡單的腳本:
// Import cloudinary
const cloudinary = require('cloudinary').v2;
// Configure cloudinary with your credentials
cloudinary.config({
cloud_name: 'your_cloud_name',
api_key: 'your_api_key',
api_secret: 'your_api_secret'
});
// Specify the public ID for the image you want to upload
const publicId = "Your_Image_ID";
// Upload the image to Cloudinary with specified options
cloudinary.uploader.upload("Path/to/your/image.png", {
resource_type: "image", // Specify the type of resource being uploaded
public_id: publicId, // Set the public ID for the uploaded image
background_removal: "cloudinary_ai" // Use background removal plugin
})
.then((result) => {
console.log("success", JSON.stringify(result, null, 2)); // Log the success response
})
.catch((error) => {
console.log("error", JSON.stringify(error, null, 2)); // Log the error response
});
希望這可以幫助你。
附言。 參考這篇博文,以防有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.