r3hab commited on
Commit
e6112da
·
verified ·
1 Parent(s): 9ba0bcc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -76
app.py CHANGED
@@ -1,84 +1,57 @@
1
- from fastapi import FastAPI, UploadFile, File
 
2
  from PIL import Image
3
  import io
4
- import os
5
- from typing import List, Optional
6
 
7
- app = FastAPI()
8
 
9
- # Supported output formats and their respective PIL modes (if applicable)
10
- supported_formats = {
11
- "png": "PNG",
12
- "jpg": "JPEG",
13
- "jpeg": "JPEG",
14
- "webp": "WEBP",
15
- "gif": "GIF", # Note: GIF conversion may lose animation if the input isn't GIF
16
- "bmp": "BMP",
17
- "tiff": "TIFF",
18
- "pdf": None, # PDF conversion handled differently
19
- }
20
 
21
-
22
-
23
- async def convert_image(image: UploadFile, output_format: str, resize: Optional[List[int]] = None):
24
-
25
- try:
26
- img_bytes = await image.read() # Read image bytes
27
- img = Image.open(io.BytesIO(img_bytes))
28
-
29
- if resize: # Resize if requested
30
- img = img.resize(tuple(resize))
31
-
32
-
33
- output_buffer = io.BytesIO()
34
-
35
- if output_format.lower() == "pdf":
36
- img.save(output_buffer, "PDF", resolution=300.0) #Higher resolution PDF
37
- content_type = "application/pdf"
38
- filename = f"{image.filename.split('.')[0]}.pdf"
39
-
40
- elif output_format.lower() in supported_formats :
41
-
42
- mode = supported_formats[output_format.lower()]
43
-
44
- # Convert image mode if necessary (e.g., for converting to grayscale)
45
- # Example usage: to convert a PNG to a grayscale JPEG
46
- # if mode:
47
- # if img.mode != 'L': #L is for grayscale
48
- # img = img.convert('L')
49
-
50
- img.save(output_buffer, mode)
51
- content_type = f"image/{output_format.lower()}" # Correct content type
52
- filename = f"{image.filename.split('.')[0]}.{output_format.lower()}"
53
- else:
54
- return {"error": "Unsupported output format"}
55
-
56
-
57
- return {
58
- "filename": filename,
59
- "file": output_buffer.getvalue(), # Return bytes
60
- "content_type": content_type,
61
- }
62
-
63
-
64
-
65
- except Exception as e: # Handle errors like invalid image format
66
- print(f"Error converting image: {e}")
67
- return {"error": f"Error converting image: {e}"}
68
-
69
-
70
- @app.post("/convert")
71
- async def convert_image_endpoint(
72
- image: UploadFile = File(...),
73
- output_format: str = "png",
74
- resize: Optional[List[int]] = None, #Example: ?resize=200&resize=300
75
  ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- return await convert_image(image, output_format, resize)
78
-
79
-
80
-
81
 
82
- @app.get("/")
83
- async def root():
84
- return {"message": "Advanced Image Converter"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ from fastapi.responses import StreamingResponse
3
  from PIL import Image
4
  import io
 
 
5
 
6
+ app = FastAPI(title="Advanced Image Converter")
7
 
8
+ ALLOWED_OUTPUT_FORMATS = ["jpeg", "png", "gif", "bmp", "tiff", "webp"]
 
 
 
 
 
 
 
 
 
 
9
 
10
+ @app.post("/convert_image/")
11
+ async def convert_image(
12
+ file: UploadFile = File(...),
13
+ output_format: str = "jpeg",
14
+ quality: int = 95 # For JPEG/WebP, adjust compression quality (0-100)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  ):
16
+ """
17
+ Converts an uploaded image to the specified format.
18
+
19
+ - Supports common image formats as input.
20
+ - Output formats: JPEG, PNG, GIF, BMP, TIFF, WebP.
21
+ - For JPEG and WebP, you can adjust the `quality` (0-100).
22
+ """
23
+ if output_format.lower() not in ALLOWED_OUTPUT_FORMATS:
24
+ raise HTTPException(
25
+ status_code=400,
26
+ detail=f"Invalid output format. Allowed formats: {', '.join(ALLOWED_OUTPUT_FORMATS)}",
27
+ )
28
+
29
+ if output_format.lower() in ["jpeg", "webp"] and not (0 <= quality <= 100):
30
+ raise HTTPException(
31
+ status_code=400, detail="Quality must be between 0 and 100 for JPEG and WebP."
32
+ )
33
 
34
+ try:
35
+ image = Image.open(io.BytesIO(await file.read()))
36
+ except Exception as e:
37
+ raise HTTPException(status_code=400, detail="Invalid image file.") from e
38
 
39
+ output_io = io.BytesIO()
40
+ try:
41
+ save_kwargs = {}
42
+ if output_format.lower() in ["jpeg", "webp"]:
43
+ save_kwargs["quality"] = quality
44
+ image.save(output_io, format=output_format.upper(), **save_kwargs)
45
+ except KeyError:
46
+ raise HTTPException(
47
+ status_code=400, detail=f"Conversion to {output_format} failed."
48
+ )
49
+ except Exception as e:
50
+ raise HTTPException(status_code=500, detail=f"Image processing error: {e}")
51
+
52
+ output_io.seek(0)
53
+ media_type = f"image/{output_format.lower()}"
54
+ if output_format.lower() == "tiff":
55
+ media_type = "image/tiff" # Special case for TIFF
56
+
57
+ return StreamingResponse(output_io, media_type=media_type)