Spaces:
Sleeping
Sleeping
| import io | |
| import base64 | |
| from PIL import Image, ImageChops, ImageEnhance | |
| def generate_ela(image: Image.Image, quality: int = 90, scale: float = 15.0) -> str: | |
| """ | |
| Performs Error Level Analysis (ELA) on an image to highlight manipulated regions. | |
| Saves the image as a temporary JPEG at a specific quality level and compares | |
| it with the original to find compression differences. | |
| Args: | |
| image: Original PIL Image. | |
| quality: JPEG compression quality for the resaved image (default 90). | |
| scale: Brightness multiplier to make the differences visible (default 15.0). | |
| Returns: | |
| Base64-encoded string of the ELA image. | |
| """ | |
| try: | |
| # Convert to RGB if necessary | |
| if image.mode != "RGB": | |
| image = image.convert("RGB") | |
| # 1. Resave the image in memory at a specific quality | |
| temp_buffer = io.BytesIO() | |
| image.save(temp_buffer, "JPEG", quality=quality) | |
| temp_buffer.seek(0) | |
| # 2. Open the resaved image | |
| resaved_img = Image.open(temp_buffer) | |
| # 3. Calculate the absolute difference between original and resaved | |
| # Manipulated areas will stand out because they compress differently | |
| ela_img = ImageChops.difference(image, resaved_img) | |
| # 4. Enhance the difference (brightness) so it's visible to the human eye | |
| enhancer = ImageEnhance.Brightness(ela_img) | |
| ela_enhanced = enhancer.enhance(scale) | |
| # 5. Convert to Base64 for the frontend | |
| out_buffer = io.BytesIO() | |
| ela_enhanced.save(out_buffer, format="JPEG", quality=85) | |
| out_buffer.seek(0) | |
| base64_str = base64.b64encode(out_buffer.read()).decode("utf-8") | |
| return f"data:image/jpeg;base64,{base64_str}" | |
| except Exception as e: | |
| print(f"[DeepGuard] ELA Generation Error: {e}") | |
| # Return empty string on failure | |
| return "" | |