Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class BackgroundRemoverModule internal constructor(context: ReactApplicationCont
}

@ReactMethod
override fun removeBackground(imageURI: String, promise: Promise) {
override fun removeBackground(imageURI: String, redValue: Int, greenValue: Int, blueValue: Int, promise: Promise) {
val segmenter = this.segmenter ?: createSegmenter()
val image = getImageBitmap(imageURI)

Expand All @@ -45,14 +45,19 @@ class BackgroundRemoverModule internal constructor(context: ReactApplicationCont

for (y in 0 until result.height) {
for (x in 0 until result.width) {
val alpha = maskBuffer.getFloat().pow(4)
mask.setPixel(x, y, Color.argb((alpha * 255).toInt(), 0, 0, 0))
val alpha = maskBuffer.getFloat()
if (alpha < 0.5f) {
image.setPixel(x, y, Color.rgb(redValue, greenValue, blueValue))
}
else {
mask.setPixel(x, y, Color.argb((alpha * 255).toInt(), 255, 255, 255))
}
}
}

val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.DST_IN))
val canvas = Canvas(image)
val canvas = Canvas()
canvas.drawBitmap(mask, 0f, 0f, paint)

val fileName = URI(imageURI).path.split("/").last()
Expand Down
2 changes: 1 addition & 1 deletion android/src/oldarch/BackgroundRemoverSpec.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ import com.facebook.react.bridge.Promise
abstract class BackgroundRemoverSpec internal constructor(context: ReactApplicationContext) :
ReactContextBaseJavaModule(context) {

abstract fun removeBackground(imageURI: String, promise: Promise)
abstract fun removeBackground(imageURI: String, redValue: Int, greenValue: Int, blueValue: Int, promise: Promise)
}
14 changes: 11 additions & 3 deletions ios/ReactNativeBackgroundRemover.mm
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#import "ReactNativeBackgroundRemover.h"
#import "ReactNativeBackgroundRemover-Swift.h"
#import "ReactNativeBackgroundRemover/ReactNativeBackgroundRemover-Swift.h"

@implementation BackgroundRemover {
BackgroundRemoverSwift *backgroundRemover;
Expand All @@ -18,10 +18,18 @@ - (id)init {
}

RCT_EXPORT_METHOD(removeBackground:(NSString *)imageURI
resolve:(RCTPromiseResolveBlock)resolve
redValue:(NSInteger)redValue
greenValue:(NSInteger)greenValue
blueValue:(NSInteger)blueValue
resolve:(RCTPromiseResolveBlock)resolve
reject:(RCTPromiseRejectBlock)reject)
{
[backgroundRemover removeBackground:imageURI resolve:resolve reject:reject];
[backgroundRemover removeBackground:imageURI
redValue:redValue
greenValue:greenValue
blueValue:blueValue
resolve:resolve
reject:reject];
}

// Don't compile this code when we build for the old architecture.
Expand Down
13 changes: 10 additions & 3 deletions ios/ReactNativeBackgroundRemover.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import CoreImage
public class BackgroundRemoverSwift: NSObject {

@objc
public func removeBackground(_ imageURI: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock)->Void {
public func removeBackground(_ imageURI: String, redValue: Int, greenValue: Int, blueValue: Int, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock)->Void {
#if targetEnvironment(simulator)
reject("BackgroundRemover", "SimulatorError", NSError(domain: "BackgroundRemover", code: 2))
return
Expand All @@ -31,11 +31,18 @@ public class BackgroundRemoverSwift: NSObject {
let scaleY = originalImage.extent.height / maskImage.extent.height
maskImage = maskImage.transformed(by: .init(scaleX: scaleX, y: scaleY))

let maskedImage = originalImage.applyingFilter("CIBlendWithMask", parameters: [kCIInputMaskImageKey: maskImage])
// Create a solid color background image
let backgroundColor = CIColor(red: CGFloat(redValue) / 255.0, green: CGFloat(greenValue) / 255.0, blue: CGFloat(blueValue) / 255.0)
let backgroundImage = CIImage(color: backgroundColor).cropped(to: originalImage.extent)

let maskedImage = originalImage.applyingFilter("CIBlendWithMask", parameters: [kCIInputImageKey: originalImage,kCIInputMaskImageKey: maskImage])

// Combine the masked image with the background
let finalImage = maskedImage.composited(over: backgroundImage)

// Save the masked image to a temporary file
let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(url.lastPathComponent)
let uiImage = UIImage(ciImage: maskedImage)
let uiImage = UIImage(ciImage: finalImage)
if let data = uiImage.pngData() {
try data.write(to: tempURL)
resolve(tempURL.absoluteString)
Expand Down
3 changes: 2 additions & 1 deletion src/NativeBackgroundRemover.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';
import { Int32 } from 'react-native/Libraries/Types/CodegenTypes';

export interface Spec extends TurboModule {
removeBackground(imageURI: string): Promise<string>;
removeBackground(imageURI: string, redValue: Int32, greenValue: Int32, blueValue: Int32): Promise<string>;
}

export default TurboModuleRegistry.getEnforcing<Spec>('BackgroundRemover');
5 changes: 3 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NativeModules, Platform } from 'react-native';
import { Int32 } from 'react-native/Libraries/Types/CodegenTypes';

const LINKING_ERROR =
`The package 'react-native-background-remover' doesn't seem to be linked. Make sure: \n\n` +
Expand Down Expand Up @@ -32,9 +33,9 @@ const BackgroundRemover = BackgroundRemoverModule
* @throws Error if the iOS device is not at least on iOS 15.0.
* @throws Error if the image could not be processed for an unknown reason.
*/
export async function removeBackground(imageURI: string): Promise<string> {
export async function removeBackground(imageURI: string, redValue: Int32, greenValue: Int32, blueValue: Int32): Promise<string> {
try {
const result: string = await BackgroundRemover.removeBackground(imageURI);
const result: string = await BackgroundRemover.removeBackground(imageURI, redValue, greenValue, blueValue);
return result;
} catch (error) {
if (error instanceof Error && error.message === 'SimulatorError') {
Expand Down