from PIL import Image
import os
import sys

def hex_to_rgb(hex_color):
    hex_color = hex_color.lstrip('#')
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))

def change_background(input_path, output_path, new_bg_color_hex="#0a192f"):
    try:
        img = Image.open(input_path).convert("RGBA")
        pixels = img.load()
        
        width, height = img.size
        # Ambil sampel warna background dari pojok kiri atas
        bg_sample = pixels[0, 0]
        
        target_r, target_g, target_b = hex_to_rgb(new_bg_color_hex)
        
        for y in range(height):
            for x in range(width):
                r, g, b, a = pixels[x, y]
                
                # Menghitung seberapa mirip pixel ini dengan background
                # Semakin kecil jaraknya, semakin mirip dengan background
                dist = ((r - bg_sample[0])**2 + (g - bg_sample[1])**2 + (b - bg_sample[2])**2)**0.5
                
                # Toleransi untuk anti-aliasing (tepi tulisan)
                max_dist = 100.0
                if dist < max_dist:
                    # Blend warna baru dengan warna asli berdasarkan jarak (untuk menghaluskan tepi)
                    ratio = dist / max_dist
                    new_r = int(target_r * (1 - ratio) + r * ratio)
                    new_g = int(target_g * (1 - ratio) + g * ratio)
                    new_b = int(target_b * (1 - ratio) + b * ratio)
                    pixels[x, y] = (new_r, new_g, new_b, a)
                    
        # Simpan sebagai PNG
        img.save(output_path, format="PNG")
        print(f"Berhasil: {output_path}")
        return True
    except Exception as e:
        print(f"Gagal memproses {input_path}: {e}")
        return False

if __name__ == "__main__":
    folder = r"D:\DLL\FILE KERJA\rizky\shopee\cv product"
    # Warna biru tua (Dark Blue)
    new_color = "#0a192f" 
    
    print("Mencari gambar dengan latar warna lain...")
    count = 0
    for f in os.listdir(folder):
        if f.lower().endswith(('.png', '.jpg', '.jpeg')) and not f.startswith("birutua_"):
            input_path = os.path.join(folder, f)
            output_path = os.path.join(folder, "birutua_" + f)
            
            # Lewati p1.png dan p2.png jika mereka sudah biru tua
            img = Image.open(input_path).convert("RGB")
            bg_color = img.getpixel((0,0))
            if bg_color[0] < 30 and bg_color[1] < 50 and bg_color[2] > 50:
                # Kemungkinan sudah biru tua
                continue
                
            print(f"Memproses {f}...")
            if change_background(input_path, output_path, new_color):
                count += 1
                
    if count == 0:
        print("Tidak ada foto baru yang perlu diubah warnanya. Pastikan foto marun sudah dimasukkan ke folder ini.")
