File size: 2,090 Bytes
4a51a09
713d623
f63ea57
 
4a51a09
f63ea57
a8a350d
b3f1777
4a51a09
f63ea57
 
4a51a09
 
f63ea57
4a51a09
f63ea57
bd2dc2e
4a51a09
f63ea57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a51a09
 
f63ea57
 
4a51a09
f63ea57
 
 
 
 
4a51a09
 
4c9a049
4a51a09
 
 
 
 
 
 
 
f63ea57
 
4a51a09
f63ea57
 
4a51a09
 
 
 
 
 
 
a8a350d
f63ea57
 
 
 
4a51a09
68e3db1
f63ea57
 
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
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from PIL import Image
import io
import vtracer
import os

app = Flask(__name__)
CORS(app, resources={r"/vectorize": {"origins": "*"}})

def convert_to_vector(image):
    input_path = "temp_input.jpg"
    output_path = "temp_output.svg"

    # Save the input image to a temporary file
    image.save(input_path)

    # Convert the image to SVG using vtracer with default settings
    vtracer.convert_image_to_svg_py(
        input_path,
        output_path,
        colormode="color",
        hierarchical="stacked",
        mode="spline",
        filter_speckle=4,
        color_precision=6,
        layer_difference=16,
        corner_threshold=60,
        length_threshold=4.0,
        max_iterations=10,
        splice_threshold=45,
        path_precision=3
    )

    # Read the SVG content
    with open(output_path, "rb") as f:
        svg_content = f.read()

    # Clean up temporary files
    os.remove(input_path)
    os.remove(output_path)

    return svg_content

@app.route('/vectorize', methods=['POST'])
def vectorize_endpoint():
    try:
        # Handle raw image data in the request body
        if request.data:
            image = Image.open(io.BytesIO(request.data)).convert('RGB')
        # Fallback for multipart/form-data
        elif 'image' in request.files:
            file = request.files['image']
            image = Image.open(file).convert('RGB')
        else:
            return jsonify({'error': 'No image data provided'}), 400

        # Process the image to SVG
        svg_content = convert_to_vector(image)

        # Return the SVG as a response
        return send_file(
            io.BytesIO(svg_content),
            mimetype='image/svg+xml',
            as_attachment=True,
            download_name='vectorized.svg'
        )
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/')
def index():
    return jsonify({'status': 'Image Vectorization API is running'})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)