pix2svg 0.1.0

Convert pixel art images to optimized SVG format
Documentation
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! # pix2svg
//!
//! A fast and efficient library to convert pixel art images to optimized SVG format.
//!
//! ## Features
//!
//! - **Optimized Output**: Uses greedy rectangle merging algorithm to minimize SVG file size
//! - **Multiple Formats**: Supports PNG, JPEG, GIF, BMP, and other common image formats via the `image` crate
//! - **Transparency Support**: Handles transparent pixels with configurable alpha threshold
//! - **Pixel Scaling**: Scale up pixel art with crisp edges
//! - **Fast Processing**: Optimized rectangle merging for efficient conversion
//!
//! ## Quick Start
//!
//! ```rust
//! use pix2svg::{convert_image_to_svg, ConversionOptions};
//! use image;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Load an image
//! let img = image::open("pixel_art.png")?;
//!
//! // Configure conversion options
//! let options = ConversionOptions {
//!     scale: 4,
//!     alpha_threshold: 1,
//!     ..Default::default()
//! };
//!
//! // Convert to SVG
//! let svg_content = convert_image_to_svg(&img, options)?;
//!
//! // Save to file
//! std::fs::write("output.svg", svg_content)?;
//! # Ok(())
//! # }
//! ```

use image::{DynamicImage, Rgba, RgbaImage};

/// Configuration options for SVG conversion
#[derive(Debug, Clone)]
pub struct ConversionOptions {
    /// Pixel scale factor (1-1000)
    pub scale: u32,
    /// Minimum alpha threshold for non-transparent pixels (0-255)
    pub alpha_threshold: u8,
    /// Skip transparent pixels (recommended for pixel art)
    pub skip_transparent: bool,
    /// Enable SVG shape-rendering="crispEdges" for pixel-perfect rendering
    pub crisp_edges: bool,
}

impl Default for ConversionOptions {
    fn default() -> Self {
        Self {
            scale: 1,
            alpha_threshold: 1,
            skip_transparent: true,
            crisp_edges: true,
        }
    }
}

/// Represents a color with RGBA components
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Color {
    /// Create a new color
    pub fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    /// Create a color from an image RGBA pixel
    pub fn from_rgba(rgba: &Rgba<u8>) -> Self {
        Self::new(rgba[0], rgba[1], rgba[2], rgba[3])
    }

    /// Check if the color is transparent based on threshold
    pub fn is_transparent(&self, threshold: u8) -> bool {
        self.a < threshold
    }

    /// Convert color to hex string (without alpha)
    pub fn to_hex(&self) -> String {
        format!("{:02X}{:02X}{:02X}", self.r, self.g, self.b)
    }

    /// Get opacity as a float (0.0 to 1.0)
    pub fn opacity(&self) -> f32 {
        self.a as f32 / 255.0
    }
}

/// Represents a rectangle with position, size, and color
#[derive(Debug, Clone)]
pub struct Rectangle {
    pub x: u32,
    pub y: u32,
    pub width: u32,
    pub height: u32,
    pub color: Color,
}

impl Rectangle {
    /// Create a new rectangle
    pub fn new(x: u32, y: u32, width: u32, height: u32, color: Color) -> Self {
        Self {
            x,
            y,
            width,
            height,
            color,
        }
    }

    /// Convert rectangle to SVG rect element
    pub fn to_svg(&self, scale: u32) -> String {
        let mut svg = format!(
            r##"<rect x="{}" y="{}" width="{}" height="{}" fill="#{}" "##,
            self.x * scale,
            self.y * scale,
            self.width * scale,
            self.height * scale,
            self.color.to_hex()
        );

        if self.color.a != 255 {
            svg.push_str(&format!(r#"opacity="{:.3}" "#, self.color.opacity()));
        }

        svg.push_str("/>");
        svg
    }

    /// Get the area of the rectangle
    pub fn area(&self) -> u64 {
        self.width as u64 * self.height as u64
    }
}

/// Internal image processor for rectangle extraction
struct ImageProcessor {
    image: RgbaImage,
    width: u32,
    height: u32,
    processed: Vec<Vec<bool>>,
    alpha_threshold: u8,
}

impl ImageProcessor {
    fn new(image: DynamicImage, alpha_threshold: u8) -> Self {
        let rgba_image = image.to_rgba8();
        let (width, height) = rgba_image.dimensions();
        let processed = vec![vec![false; width as usize]; height as usize];

        Self {
            image: rgba_image,
            width,
            height,
            processed,
            alpha_threshold,
        }
    }

    fn get_pixel_color(&self, x: u32, y: u32) -> Option<Color> {
        if x >= self.width || y >= self.height {
            return None;
        }

        let pixel = self.image.get_pixel(x, y);
        let color = Color::from_rgba(pixel);

        if color.is_transparent(self.alpha_threshold) {
            None
        } else {
            Some(color)
        }
    }

    fn is_processed(&self, x: u32, y: u32) -> bool {
        self.processed[y as usize][x as usize]
    }

    fn mark_processed(&mut self, rect: &Rectangle) {
        for y in rect.y..rect.y + rect.height {
            for x in rect.x..rect.x + rect.width {
                self.processed[y as usize][x as usize] = true;
            }
        }
    }

    fn find_max_rectangle(&self, start_x: u32, start_y: u32, color: Color) -> Rectangle {
        // Find maximum width for the current row
        let mut max_width = 0;
        for x in start_x..self.width {
            if self.is_processed(x, start_y) {
                break;
            }
            if let Some(pixel_color) = self.get_pixel_color(x, start_y) {
                if pixel_color != color {
                    break;
                }
                max_width = x - start_x + 1;
            } else {
                break;
            }
        }

        // Find maximum height with the current width
        let mut max_height = 0;
        for y in start_y..self.height {
            let mut can_extend = true;
            for x in start_x..start_x + max_width {
                if self.is_processed(x, y) {
                    can_extend = false;
                    break;
                }
                if let Some(pixel_color) = self.get_pixel_color(x, y) {
                    if pixel_color != color {
                        can_extend = false;
                        break;
                    }
                } else {
                    can_extend = false;
                    break;
                }
            }
            if !can_extend {
                break;
            }
            max_height = y - start_y + 1;
        }

        Rectangle::new(start_x, start_y, max_width, max_height, color)
    }

    fn extract_rectangles(&mut self) -> Vec<Rectangle> {
        let mut rectangles = Vec::new();

        for y in 0..self.height {
            for x in 0..self.width {
                if self.is_processed(x, y) {
                    continue;
                }

                if let Some(color) = self.get_pixel_color(x, y) {
                    let rect = self.find_max_rectangle(x, y, color);
                    self.mark_processed(&rect);
                    rectangles.push(rect);
                } else {
                    // Mark transparent pixel as processed
                    self.processed[y as usize][x as usize] = true;
                }
            }
        }

        rectangles
    }
}

/// Conversion result containing SVG content and statistics
#[derive(Debug, Clone)]
pub struct ConversionResult {
    /// The generated SVG content
    pub svg_content: String,
    /// Number of rectangles generated
    pub rectangle_count: usize,
    /// Original image dimensions
    pub image_dimensions: (u32, u32),
}

impl ConversionResult {
    /// Get the length of the SVG content in bytes
    pub fn svg_size_bytes(&self) -> usize {
        self.svg_content.len()
    }
}

/// Convert a dynamic image to SVG format with given options
///
/// # Arguments
///
/// * `image` - The input image to convert
/// * `options` - Conversion options
///
/// # Returns
///
/// Returns a `ConversionResult` containing the SVG content and statistics
///
/// # Example
///
/// ```rust
/// use pix2svg::{convert_image_to_svg, ConversionOptions};
/// use image;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let img = image::open("test.png")?;
/// let options = ConversionOptions::default();
/// let result = convert_image_to_svg(&img, options)?;
/// println!("Generated {} rectangles", result.rectangle_count);
/// # Ok(())
/// # }
/// ```
pub fn convert_image_to_svg(
    image: &DynamicImage,
    options: ConversionOptions,
) -> Result<ConversionResult, Box<dyn std::error::Error>> {
    let width = image.width();
    let height = image.height();

    // Process image and extract rectangles
    let mut processor = ImageProcessor::new(image.clone(), options.alpha_threshold);
    let rectangles = processor.extract_rectangles();

    // Generate SVG content
    let svg_content = create_svg(&rectangles, width, height, &options);

    Ok(ConversionResult {
        svg_content,
        rectangle_count: rectangles.len(),
        image_dimensions: (width, height),
    })
}

/// Create SVG content from rectangles
fn create_svg(
    rectangles: &[Rectangle],
    width: u32,
    height: u32,
    options: &ConversionOptions,
) -> String {
    let mut svg = String::new();

    // XML declaration and SVG opening tag
    svg.push_str(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
    svg.push('\n');

    let mut svg_tag = format!(
        r#"<svg version="1.1" width="{}" height="{}" xmlns="http://www.w3.org/2000/svg""#,
        width * options.scale,
        height * options.scale
    );

    if options.crisp_edges {
        svg_tag.push_str(r#" shape-rendering="crispEdges""#);
    }

    svg_tag.push('>');
    svg.push_str(&svg_tag);
    svg.push('\n');

    // Add rectangles
    for rect in rectangles {
        svg.push_str(&rect.to_svg(options.scale));
        svg.push('\n');
    }

    // Closing tag
    svg.push_str("</svg>");
    svg.push('\n');

    svg
}

/// Convert image file path to SVG format
///
/// # Arguments
///
/// * `input_path` - Path to the input image file
/// * `options` - Conversion options
///
/// # Returns
///
/// Returns a `ConversionResult` containing the SVG content and statistics
pub fn convert_file_to_svg<P: AsRef<std::path::Path>>(
    input_path: P,
    options: ConversionOptions,
) -> Result<ConversionResult, Box<dyn std::error::Error>> {
    let image = image::open(input_path)?;
    convert_image_to_svg(&image, options)
}

/// Save SVG content to a file
///
/// # Arguments
///
/// * `svg_content` - The SVG content to save
/// * `output_path` - Path where to save the SVG file
pub fn save_svg_to_file<P: AsRef<std::path::Path>>(
    svg_content: &str,
    output_path: P,
) -> Result<(), Box<dyn std::error::Error>> {
    std::fs::write(output_path, svg_content)?;
    Ok(())
}

/// Save SVG content to a file with overwrite protection
///
/// # Arguments
///
/// * `svg_content` - The SVG content to save
/// * `output_path` - Path where to save the SVG file
/// * `force_overwrite` - Whether to overwrite existing files
///
/// # Returns
///
/// Returns an error if the file exists and `force_overwrite` is false
pub fn save_svg_to_file_safe<P: AsRef<std::path::Path>>(
    svg_content: &str,
    output_path: P,
    force_overwrite: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = output_path.as_ref();

    if path.exists() && !force_overwrite {
        return Err(format!("File already exists: {:?}", path).into());
    }

    std::fs::write(path, svg_content)?;
    Ok(())
}