from utils import render
from models import Image
import os
from java.io import File, ByteArrayInputStream
from javax.imageio import ImageIO
from java.awt.image import BufferedImage
from java.awt import RenderingHints
from com.google.common.io import Files
class Image_upload(object):
def view(self, ctx):
# Show recent uploads
recent_images = Image.findAll().orderBy("created_at DESC").limit(6)
ctx.output["recent_images"] = recent_images
ctx.go_to = render.as_view(ctx, "image_upload")
def upload(self, ctx):
try:
request = ctx.getRequest()
# Get uploaded image using SØAD's built-in file handling
image_content = request.getParameter("image") # Image content as bytes
image_type = request.getParameter("image_ft") # MIME type
image_name = request.getParameter("image_fn") # Original filename
if image_content and image_name:
# Validate image type
if not image_type or not image_type.startswith("image/"):
ctx.output["error"] = "Please upload a valid image file"
ctx.go_to = render.as_view(ctx, "image_upload")
return
# Validate file size (2MB for images)
file_size = len(image_content)
if file_size > 2 * 1024 * 1024:
ctx.output["error"] = "Image size must be less than 2MB"
ctx.go_to = render.as_view(ctx, "image_upload")
return
# Create upload directories
upload_base = os.path.join(ctx.getRealPath(), "uploads", "images")
original_dir = os.path.join(upload_base, "original")
thumbnail_dir = os.path.join(upload_base, "thumbnails")
for directory in [original_dir, thumbnail_dir]:
if not os.path.exists(directory):
os.makedirs(directory)
# Generate safe filename
safe_filename = os.path.basename(image_name)
original_path = os.path.join(original_dir, safe_filename)
# Save original image
original_file = File(original_path)
Files.write(image_content, original_file)
# Create thumbnail
thumbnail_path = self.create_thumbnail(ctx, image_content, safe_filename, thumbnail_dir)
# Save to database
image = Image()
image.set("filename", safe_filename)
image.set("original_path", original_path)
image.set("thumbnail_path", thumbnail_path)
image.set("file_size", file_size)
image.set("content_type", image_type)
image.saveIt()
ctx.output["success"] = "Image uploaded and processed successfully!"
ctx.output["uploaded_image"] = image
else:
ctx.output["error"] = "Please select an image to upload"
except Exception as e:
ctx.output["error"] = "Upload failed: " + str(e)
# Reload recent images
recent_images = Image.findAll().orderBy("created_at DESC").limit(6)
ctx.output["recent_images"] = recent_images
ctx.go_to = render.as_view(ctx, "image_upload")
def create_thumbnail(self, ctx, image_bytes, filename, thumbnail_dir):
"""Create a thumbnail version of the uploaded image"""
try:
# Read image from byte array
input_stream = ByteArrayInputStream(image_bytes)
original_image = ImageIO.read(input_stream)
if original_image:
# Calculate thumbnail dimensions (max 150x150)
orig_width = original_image.getWidth()
orig_height = original_image.getHeight()
thumb_width = 150
thumb_height = 150
# Maintain aspect ratio
if orig_width > orig_height:
thumb_height = int((float(orig_height) / orig_width) * thumb_width)
else:
thumb_width = int((float(orig_width) / orig_height) * thumb_height)
# Create thumbnail
thumbnail = BufferedImage(thumb_width, thumb_height, BufferedImage.TYPE_INT_RGB)
graphics = thumbnail.createGraphics()
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
graphics.drawImage(original_image, 0, 0, thumb_width, thumb_height, None)
graphics.dispose()
# Save thumbnail
thumb_filename = "thumb_" + filename
thumbnail_path = os.path.join(thumbnail_dir, thumb_filename)
# Save as JPEG for consistent format
ImageIO.write(thumbnail, "jpg", File(thumbnail_path))
return thumbnail_path
except Exception as e:
print("Thumbnail creation failed: " + str(e))
return None