File size: 1,966 Bytes
a02f72f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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 ""