### Integrate Background Removal in Node.js Source: https://github.com/photoroom/api-code-samples/blob/main/README.md Shows how to import and use the removeBackground module in a Node.js environment. It processes a local image file and saves the output to a specified path using promises. ```javascript const removeBackground = require('./remove-background'); const imagePath = './path/to/your/image.jpg'; const savePath = './path/where/you/want/to/save/response.jpg'; removeBackground(imagePath, savePath) .then(message => { console.log(message); }) .catch(error => { console.error('Error:', error); }); ``` -------------------------------- ### Web/TypeScript Implementation Source: https://context7.com/photoroom/api-code-samples/llms.txt An asynchronous function that sends an image file to the Photoroom API and returns the processed image as a Blob. This implementation uses the Fetch API and handles multipart form data construction. ```APIDOC ## removeBackground(imageFile: File): Promise ### Description Sends an image file to the Photoroom API for background removal and returns the processed image as a Blob. ### Method Asynchronous function ### Parameters - **imageFile** (File) - Required - The image file to process. ### Returns - Promise - A Promise that resolves with the processed image as a Blob. ### Request Example ```typescript // remove-background.ts const url = 'https://sdk.photoroom.com/v1/segment'; const apiKey = "YOUR_API_KEY_HERE"; export async function removeBackground(imageFile: File): Promise { const formData = new FormData(); formData.append('image_file', imageFile); const response = await fetch(url, { method: 'POST', headers: { 'X-Api-Key': apiKey }, body: formData }); if (!response.ok) { console.error(response.json()) throw new Error('Network response was not ok'); } const imageBlob: Blob = await response.blob(); return imageBlob; } // Usage in a web application import { removeBackground } from './remove-background.js'; const fileInput = document.getElementById('fileInput') as HTMLInputElement; const displayImage = document.getElementById('displayImage') as HTMLImageElement; fileInput.addEventListener('change', async () => { const files = fileInput.files; if (files && files.length > 0) { try { const imageBlob = await removeBackground(files[0]); const objectURL = URL.createObjectURL(imageBlob); displayImage.src = objectURL; } catch (error) { console.error('Error:', error); } } }); ``` ### Response Example (Blob object representing the processed image) ``` -------------------------------- ### Remove Background in iOS Source: https://github.com/photoroom/api-code-samples/blob/main/README.md Demonstrates how to invoke the background removal function on an image. It provides two approaches: one using Swift Concurrency (async/await) and one using a completion handler for older codebases. ```swift Task { @MainActor in imageView.image = try await removeBackground(of: yourImage) } ``` ```swift removeBackground(of: yourImage) { result in switch result { case let .success(backgroundRemoved): imageView.image = backgroundRemoved case let .failure(error): // handle the error } } ``` -------------------------------- ### Integrate Background Removal in Web Applications Source: https://github.com/photoroom/api-code-samples/blob/main/README.md Demonstrates how to use the removeBackground function in a browser environment. It listens for file input changes, processes the image, and updates an HTML image element with the result. ```javascript import { removeBackground } from './remove-background.js'; const fileInput = document.getElementById('fileInput') as HTMLInputElement; const displayImage = document.getElementById('displayImage') as HTMLImageElement; fileInput.addEventListener('change', async () => { const files = fileInput.files; if (files && files.length > 0) { try { const imageBlob = await removeBackground(files[0]); const objectURL = URL.createObjectURL(imageBlob); displayImage.src = objectURL; } catch (error) { console.error('Error:', error); } } }); ``` -------------------------------- ### Integrate Background Removal in Python Source: https://github.com/photoroom/api-code-samples/blob/main/README.md Provides a simple interface for calling the background removal function in Python. It takes an input image path and an output path to save the processed result. ```python from remove_background import remove_background # Example usage input_path = "test.jpg" output_path = "result.png" remove_background(input_path, output_path) ``` -------------------------------- ### Remove Background via cURL Source: https://context7.com/photoroom/api-code-samples/llms.txt Demonstrates how to perform a background removal request using the command line. It sends an image file to the /v1/segment endpoint and saves the resulting transparent image to a local file. ```bash curl -X POST "https://sdk.photoroom.com/v1/segment" \ -H "X-Api-Key: YOUR_API_KEY" \ -F "image_file=@/path/to/your/image.jpg" \ --output result.png ``` -------------------------------- ### Node.js - Remove Background Source: https://context7.com/photoroom/api-code-samples/llms.txt This Node.js function reads an image from the local filesystem, sends it to the Photoroom API for background removal, and saves the processed image to a specified path using streams for efficiency. ```APIDOC ## POST /v1/segment ### Description Removes the background from an image by sending it to the Photoroom API. ### Method POST ### Endpoint https://sdk.photoroom.com/v1/segment ### Parameters #### Request Body - **image_file** (file) - Required - The image file to process. ### Request Example ```javascript // Usage example const removeBackground = require('./remove-background'); const imagePath = './test.jpg'; const savePath = './result.png'; removeBackground(imagePath, savePath) .then(message => { console.log(message); }) .catch(error => { console.error('Error:', error); }); ``` ### Response #### Success Response (200) - The processed image data (e.g., PNG, JPEG). #### Response Example (Binary image data) ``` -------------------------------- ### Remove Background using Swift Source: https://context7.com/photoroom/api-code-samples/llms.txt An asynchronous Swift function that removes the background from a UIImage using the Photoroom API. It includes automatic image scaling for performance and comprehensive error handling. The function supports both Swift Concurrency (async/await) and completion handlers. ```swift // RemoveBackground.swift import UIKit private let apiKey: String = "YOUR_API_KEY" private let hostURL = URL(string: "https://sdk.photoroom.com/v1/segment")! public enum RemoveBackgroundError: Error, LocalizedError { case invalidData case serverError case noAPIKey public var errorDescription: String? { switch self { case .invalidData: return "Data of image is not valid." case .serverError: return "There was a server error." case .noAPIKey: return "There is no key for the PhotoRoom API." } } } // Async/await version (Swift Concurrency) public func removeBackground(of image: UIImage) async throws -> UIImage { return try await withCheckedThrowingContinuation { continuation in removeBackground(of: image) { result in continuation.resume(with: result) } } } // Completion handler version public func removeBackground( of image: UIImage, completionHandler: @escaping (Result) -> Void ) { guard !apiKey.isEmpty else { completionHandler(.failure(.noAPIKey)) return } var request = URLRequest(url: hostURL) request.httpMethod = "POST" request.timeoutInterval = 30.0 // Scale image to max 1000x1000 for optimal performance let scale = image.scaled(maxDimensions: CGSize(width: 1000, height: 1000)) let scaledImage = image.scaled(by: scale) let boundary = "Boundary-\(UUID().uuidString)" request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.addValue(apiKey, forHTTPHeaderField: "X-Api-Key") // Build multipart body with image data guard let imageData = scaledImage.jpegData(compressionQuality: 0.7) else { completionHandler(.failure(.invalidData)) return } var body = Data() body.append("--\(boundary)\r\n".data(using: .utf8)!) body.append("Content-Disposition: form-data; name=\"image_file\"; filename=\"image.jpg\"\r\n".data(using: .utf8)!) body.append("Content-Type: image/jpg\r\n\r\n".data(using: .utf8)!) body.append(imageData) body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!) request.httpBody = body URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil, (200...299).contains(httpResponse.statusCode), let image = UIImage(data: data) else { completionHandler(.failure(.serverError)) return } completionHandler(.success(image)) }.resume() } // Usage with Swift Concurrency Task { @MainActor in do { let originalImage = UIImage(named: "sample_image.jpg")! let backgroundRemoved = try await removeBackground(of: originalImage) // imageView.image = backgroundRemoved } catch { print("Error: \(error.localizedDescription)") } } // Usage with completion handler // removeBackground(of: yourImage) { result in // switch result { // case let .success(backgroundRemoved): // DispatchQueue.main.async { // // imageView.image = backgroundRemoved // } // case let .failure(error): // print("Error: \(error.localizedDescription)") // } // } ``` -------------------------------- ### Remove Background in TypeScript Source: https://context7.com/photoroom/api-code-samples/llms.txt An asynchronous implementation for browser environments using the Fetch API. It constructs a FormData object to upload the image and returns the processed result as a Blob. ```typescript const url = 'https://sdk.photoroom.com/v1/segment'; const apiKey = "YOUR_API_KEY_HERE"; export async function removeBackground(imageFile: File): Promise { const formData = new FormData(); formData.append('image_file', imageFile); const response = await fetch(url, { method: 'POST', headers: { 'X-Api-Key': apiKey }, body: formData }); if (!response.ok) { console.error(response.json()) throw new Error('Network response was not ok'); } const imageBlob: Blob = await response.blob(); return imageBlob; } ``` -------------------------------- ### Remove Background using Node.js Source: https://context7.com/photoroom/api-code-samples/llms.txt A Node.js function that removes the background of an image using the Photoroom API. It reads an image from the local filesystem, sends it via HTTPS POST request with multipart/form-data encoding, and saves the processed image to a specified path. Uses native 'https' and 'fs' modules for efficient streaming. ```javascript const https = require('https'); const fs = require('fs'); const apiKey = 'YOUR_API_KEY_HERE'; function removeBackground(imagePath, savePath) { return new Promise((resolve, reject) => { const boundary = '--------------------------' + Date.now().toString(16); const postOptions = { hostname: 'sdk.photoroom.com', path: '/v1/segment', method: 'POST', headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}`, 'X-API-Key': apiKey } }; const req = https.request(postOptions, (res) => { const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(res.headers['content-type']); if (!isImage) { let errorData = ''; res.on('data', (chunk) => errorData += chunk); res.on('end', () => reject(new Error(`Expected an image response, but received: ${errorData}`))); return; } const fileStream = fs.createWriteStream(savePath); res.pipe(fileStream); fileStream.on('finish', () => { resolve(`Image saved to ${savePath}`); }); fileStream.on('error', (error) => { reject(new Error(`Failed to save the image: ${error.message}`)); }); }); req.on('error', (error) => { reject(error); }); req.write(`--${boundary}\r\n`); req.write(`Content-Disposition: form-data; name="image_file"; filename="${imagePath.split('/').pop()}"\r\n`); req.write('Content-Type: image/jpeg\r\n\r\n'); const uploadStream = fs.createReadStream(imagePath); uploadStream.on('end', () => { req.write('\r\n'); req.write(`--${boundary}--\r\n`); req.end(); }); uploadStream.pipe(req, { end: false }); }); } module.exports = removeBackground; // Usage example const removeBackground = require('./remove-background'); const imagePath = './test.jpg'; const savePath = './result.png'; removeBackground(imagePath, savePath) .then(message => { console.log(message); // Output: Image saved to ./result.png }) .catch(error => { console.error('Error:', error); }); ``` -------------------------------- ### Remove Background using Python Source: https://context7.com/photoroom/api-code-samples/llms.txt A Python function that removes the background of an image using the Photoroom API. It reads an image file, sends it via an HTTPS POST request with multipart/form-data encoding, and saves the processed image to a specified output path. This implementation uses Python's 'http.client' and 'mimetypes' modules and automatically detects the image MIME type. ```python # remove_background.py import http.client import mimetypes import os import uuid apiKey = 'YOUR_API_KEY_HERE' def remove_background(input_image_path, output_image_path): # Define multipart boundary boundary = '----------{}'.format(uuid.uuid4().hex) # Get mimetype of image content_type, _ = mimetypes.guess_type(input_image_path) if content_type is None: content_type = 'application/octet-stream' # Prepare the POST data with open(input_image_path, 'rb') as f: image_data = f.read() filename = os.path.basename(input_image_path) body = ( f"--{boundary}\r\n" f"Content-Disposition: form-data; name=\"image_file\"; filename=\"{filename}\"\r\n" f"Content-Type: {content_type}\r\n\r\n" ).encode('utf-8') + image_data + f"\r\n--{boundary}--\r\n".encode('utf-8') # Set up the HTTP connection and headers conn = http.client.HTTPSConnection('sdk.photoroom.com') headers = { 'Content-Type': f'multipart/form-data; boundary={boundary}', 'x-api-key': apiKey } # Make the POST request conn.request('POST', '/v1/segment', body=body, headers=headers) response = conn.getresponse() # Handle the response if response.status == 200: response_data = response.read() with open(output_image_path, 'wb') as out_f: out_f.write(response_data) print("Image saved to", output_image_path) else: print(f"Error: {response.status} - {response.reason}") print(response.read()) conn.close() # Usage example from remove_background import remove_background input_path = "test.jpg" output_path = "result.png" remove_background(input_path, output_path) # Output: Image saved to result.png ``` -------------------------------- ### Python - Remove Background Source: https://context7.com/photoroom/api-code-samples/llms.txt This Python function synchronously removes the background from an image. It reads the image file, sends it to the Photoroom API using http.client, and saves the result. It automatically detects the image MIME type. ```APIDOC ## POST /v1/segment ### Description Removes the background from an image by sending it to the Photoroom API. ### Method POST ### Endpoint https://sdk.photoroom.com/v1/segment ### Parameters #### Request Body - **image_file** (file) - Required - The image file to process. ### Request Example ```python # Usage example from remove_background import remove_background input_path = "test.jpg" output_path = "result.png" remove_background(input_path, output_path) ``` ### Response #### Success Response (200) - The processed image data (e.g., PNG, JPEG). #### Response Example (Binary image data) ``` -------------------------------- ### Remove Background API Endpoint Source: https://context7.com/photoroom/api-code-samples/llms.txt This endpoint removes the background from an uploaded image using AI and returns the processed image with a transparent background. It accepts multipart form data and returns the image directly. ```APIDOC ## POST /v1/segment ### Description Removes the background from an uploaded image and returns the processed image with a transparent background. ### Method POST ### Endpoint https://sdk.photoroom.com/v1/segment ### Parameters #### Request Body - **image_file** (file) - Required - The image file to process. ### Request Example ```bash curl -X POST "https://sdk.photoroom.com/v1/segment" \ -H "X-Api-Key: YOUR_API_KEY" \ -F "image_file=@/path/to/your/image.jpg" \ --output result.png ``` ### Response #### Success Response (200) - **Content-Type**: image/png - The processed image with a transparent background. #### Response Example (Binary image data) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.