File size: 7,752 Bytes
6aa31ae
 
1988036
6aa31ae
 
 
 
1988036
6aa31ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c322288
 
6aa31ae
c322288
 
 
6aa31ae
c322288
 
 
 
 
 
 
 
 
 
 
6aa31ae
 
 
1988036
6aa31ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1988036
 
 
 
6aa31ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import io
import os
import shutil
import zipfile
import streamlit as st
from PIL import Image as PILImage

from helper import extract_zip_to_temp, ALLOWED_IMAGE_EXTENSIONS


def center_on_canvas_tool():
    st.header("Center on Transparent Canvas")
    st.markdown("Center small images on a transparent 500x500 canvas.")
    
    # File upload - add unique key
    uploaded_file = st.file_uploader(
        "Choose a ZIP file with images",
        type=['zip'],
        help="Upload a zip file containing images to process.",
        key="canvas_center_upload"  # Added unique key
    )
    
    if uploaded_file:
        # Size picker: standard 500, high-res 1500, or a custom value.
        size_choice = st.selectbox(
            "Canvas size (pixels):",
            options=["500", "1500", "Custom…"],
            index=0,
            key="canvas_size_choice",
        )
        if size_choice == "Custom…":
            canvas_size = int(st.number_input(
                "Custom canvas size (pixels):",
                min_value=100,
                max_value=10000,
                value=500,
                step=10,
                key="canvas_size_input",
            ))
        else:
            canvas_size = int(size_choice)
        
        # Add unique key to the button
        if st.button("Process Images", type="primary", key="process_canvas_images"):
            temp_dir = None
            try:
                # Extract zip file
                with st.spinner("Extracting zip file..."):
                    temp_dir = extract_zip_to_temp(uploaded_file)
                    input_folder = temp_dir
                    items = os.listdir(temp_dir)
                    if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
                        input_folder = os.path.join(temp_dir, items[0])
                
                # Create output folder
                output_folder = os.path.join(temp_dir, "canvas_output")
                os.makedirs(output_folder, exist_ok=True)
                
                # Process images
                processed_count = 0
                progress_bar = st.progress(0)
                status_text = st.empty()
                
                all_files = []
                for root, dirs, files in os.walk(input_folder):
                    for file in files:
                        ext = os.path.splitext(file)[1].lower()
                        if ext in ALLOWED_IMAGE_EXTENSIONS:
                            all_files.append(os.path.join(root, file))
                
                for i, file_path in enumerate(all_files):
                    status_text.text(f"Processing {os.path.basename(file_path)}... ({i+1}/{len(all_files)})")
                    progress_bar.progress((i + 1) / len(all_files))
                    
                    try:
                        with PILImage.open(file_path) as img:
                            width, height = img.size
                            
                            if width < canvas_size and height < canvas_size:
                                # Create transparent canvas
                                canvas = PILImage.new('RGBA', (canvas_size, canvas_size), (255, 255, 255, 0))
                                
                                # Convert image to RGBA if needed
                                if img.mode != 'RGBA':
                                    img = img.convert('RGBA')
                                
                                # Center image on canvas
                                paste_x = (canvas_size - width) // 2
                                paste_y = (canvas_size - height) // 2
                                canvas.paste(img, (paste_x, paste_y), img)
                                
                                # Save processed image
                                new_filename = os.path.splitext(os.path.basename(file_path))[0] + ".png"
                                output_path = os.path.join(output_folder, new_filename)
                                canvas.save(output_path)
                                processed_count += 1
                    except Exception as e:
                        st.warning(f"Error processing {os.path.basename(file_path)}: {str(e)}")
                
                status_text.empty()
                progress_bar.empty()
                
                if processed_count > 0:
                    st.success(f"✅ Successfully processed {processed_count} images")
                    
                    # Create zip file with processed images
                    zip_buffer = io.BytesIO()
                    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
                        for root, dirs, files in os.walk(output_folder):
                            for file in files:
                                file_path = os.path.join(root, file)
                                rel_path = os.path.relpath(file_path, output_folder)
                                zip_file.write(file_path, rel_path)
                    
                    zip_buffer.seek(0)
                    
                    # Download button
                    st.download_button(
                        label="📥 Download Processed Images (ZIP)",
                        data=zip_buffer.getvalue(),
                        file_name="centered_images.zip",
                        mime="application/zip"
                    )
                    
                    # Show preview
                    with st.expander("🖼️ Preview Processed Images"):
                        sample_files = []
                        for root, dirs, files in os.walk(output_folder):
                            for file in files[:3]:  # Get first 3 files from each folder
                                if len(sample_files) < 6:  # Max 6 samples
                                    sample_files.append(os.path.join(root, file))
                        
                        cols = st.columns(3)
                        for i, file_path in enumerate(sample_files):
                            with cols[i % 3]:
                                img = PILImage.open(file_path)
                                st.image(img, caption=os.path.basename(file_path), use_column_width=True)
                        
                        if processed_count > 6:
                            st.info(f"Showing sample images. Total processed: {processed_count}")
                else:
                    st.warning("No images were processed (all images were already larger than the canvas size).")
            
            except Exception as e:
                st.error(f"An error occurred: {str(e)}")
            finally:
                if temp_dir:
                    shutil.rmtree(temp_dir, ignore_errors=True)

    else:
        st.info("👆 Please upload a zip file with images to process.")
        
        # Instructions
        with st.expander("📖 Instructions"):
            st.markdown("""
            **How to use this tool:**
            
            1. Upload a zip file containing images
            2. Set the canvas size (default is 500x500 pixels)
            3. Click "Process Images"
            4. Download the processed images
            
            **Features:**
            - Centers images smaller than canvas size on transparent background
            - Images larger than canvas size are skipped
            - Outputs PNG files to preserve transparency
            - Preserves folder structure
            
            **Note:**
            - Only images smaller than the specified canvas size will be processed
            - Original aspect ratio is maintained
            """)