[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H9XR5DT9NB0GPR2D0WTSJH":3,"skill-same:01M6H9XR5DT9NB0GPR2D0WTSJH":54},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":24,"linkOnly":25,"markdownContent":26,"markdownBody":27,"frontMatter":28,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":14,"repositoryHtmlUrl":35,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":37,"ownerDescription":38,"updatedAt":39,"install":40,"resources":53},"01M6H9XR5DT9NB0GPR2D0WTSJH","image-processing",null,"Image processing and manipulation","NeuralBlitz\u002FMito","NeuralBlitz","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F79354388?v=4","01M6H8T2TFH477HRS0KTSTKR2E","David Riggs","01M6H8T2YQQDXPYM092P670Z21",0,"MIT","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fimage-processing\u002FSKILL.md",[],[19,20,21,22,23],"image","image processing","processing","opencode","Utilities","2026-11-10 10:12:30",false,"---\nname: image-processing\ndescription: Image processing and manipulation\nlicense: MIT\ncompatibility: opencode\nmetadata:\n  audience: developers\n  category: utilities\n---\n## What I do\n- Resize and transform images\n- Handle image formats\n- Optimize image quality\n- Generate thumbnails\n- Extract image metadata\n- Apply filters and effects\n- Handle image uploads securely\n- Serve optimized images\n\n## When to use me\nWhen implementing image processing or handling image uploads.\n\n## Image Processing Basics\n```python\nfrom PIL import Image, ImageFilter, ImageEnhance\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Optional, List, Tuple\nimport io\n\n\n@dataclass\nclass ImageDimensions:\n    \"\"\"Image dimensions.\"\"\"\n    width: int\n    height: int\n    \n    @property\n    def aspect_ratio(self) -> float:\n        return self.width \u002F self.height\n    \n    def resize(self, max_width: int, max_height: int) -> 'ImageDimensions':\n        \"\"\"Resize while maintaining aspect ratio.\"\"\"\n        ratio = min(max_width \u002F self.width, max_height \u002F self.height)\n        return ImageDimensions(\n            width=int(self.width * ratio),\n            height=int(self.height * ratio)\n        )\n\n\n@dataclass\nclass ImageConfig:\n    \"\"\"Image processing configuration.\"\"\"\n    format: str = \"JPEG\"\n    quality: int = 85\n    optimize: bool = True\n    preserve_metadata: bool = False\n\n\nclass ImageProcessor:\n    \"\"\"Image processing operations.\"\"\"\n    \n    def __init__(self, config: ImageConfig = None):\n        self.config = config or ImageConfig()\n    \n    def open(self, image_path: Path) -> Image:\n        \"\"\"Open an image file.\"\"\"\n        return Image.open(image_path)\n    \n    def resize(\n        self,\n        image: Image,\n        width: int,\n        height: int,\n        maintain_aspect: bool = True\n    ) -> Image:\n        \"\"\"Resize image.\"\"\"\n        if maintain_aspect:\n            current_dims = ImageDimensions(image.width, image.height)\n            new_dims = current_dims.resize(width, height)\n            width, height = new_dims.width, new_dims.height\n        \n        return image.resize((width, height), Image.LANCZOS)\n    \n    def create_thumbnail(\n        self,\n        image: Image,\n        max_size: Tuple[int, int] = (300, 300)\n    ) -> Image:\n        \"\"\"Create thumbnail preserving aspect ratio.\"\"\"\n        image.thumbnail(max_size, Image.LANCZOS)\n        return image\n    \n    def crop(\n        self,\n        image: Image,\n        left: int,\n        top: int,\n        right: int,\n        bottom: int\n    ) -> Image:\n        \"\"\"Crop image.\"\"\"\n        return image.crop((left, top, right, bottom))\n    \n    def rotate(self, image: Image, degrees: float) -> Image:\n        \"\"\"Rotate image.\"\"\"\n        return image.rotate(-degrees, expand=True)\n    \n    def flip_horizontal(self, image: Image) -> Image:\n        \"\"\"Flip image horizontally.\"\"\"\n        return image.transpose(Image.FLIP_LEFT_RIGHT)\n    \n    def flip_vertical(self, image: Image) -> Image:\n        \"\"\"Flip image vertically.\"\"\"\n        return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\nclass ImageFilterApplier:\n    \"\"\"Apply filters to images.\"\"\"\n    \n    @staticmethod\n    def blur(image: Image, radius: float = 2) -> Image:\n        \"\"\"Apply Gaussian blur.\"\"\"\n        return image.filter(ImageFilter.GaussianBlur(radius))\n    \n    @staticmethod\n    def sharpen(image: Image) -> Image:\n        \"\"\"Sharpen image.\"\"\"\n        return image.filter(ImageFilter.SHARPEN)\n    \n    @staticmethod\n    def contour(image: Image) -> Image:\n        \"\"\"Apply contour filter.\"\"\"\n        return image.filter(ImageFilter.CONTOUR)\n    \n    @staticmethod\n    def edge_enhance(image: Image) -> Image:\n        \"\"\"Edge enhancement.\"\"\"\n        return image.filter(ImageFilter.EDGE_ENHANCE)\n    \n    @staticmethod\n    def emboss(image: Image) -> Image:\n        \"\"\"Apply emboss effect.\"\"\"\n        return image.filter(ImageFilter.EMBOSS)\n    \n    @staticmethod\n    def adjust_brightness(image: Image, factor: float) -> Image:\n        \"\"\"Adjust brightness.\"\"\"\n        enhancer = ImageEnhance.Brightness(image)\n        return enhancer.enhance(factor)\n    \n    @staticmethod\n    def adjust_contrast(image: Image, factor: float) -> Image:\n        \"\"\"Adjust contrast.\"\"\"\n        enhancer = ImageEnhance.Contrast(image)\n        return enhancer.enhance(factor)\n    \n    @staticmethod\n    def adjust_saturation(image: Image, factor: float) -> Image:\n        \"\"\"Adjust saturation.\"\"\"\n        enhancer = ImageEnhance.Color(image)\n        return enhancer.enhance(factor)\n\n\nclass ImageOptimizer:\n    \"\"\"Optimize images for web.\"\"\"\n    \n    def __init__(self, config: ImageConfig = None):\n        self.config = config or ImageConfig()\n    \n    def optimize(\n        self,\n        image: Image,\n        output_format: str = None\n    ) -> Image:\n        \"\"\"Optimize image.\"\"\"\n        format = output_format or self.config.format\n        \n        if format.upper() == \"JPEG\":\n            image = image.convert(\"RGB\")\n        \n        return image\n    \n    def save_with_quality(\n        self,\n        image: Image,\n        output_path: Path,\n        quality: int = None,\n        format: str = None\n    ) -> None:\n        \"\"\"Save image with specific quality.\"\"\"\n        quality = quality or self.config.quality\n        format = format or self.config.format\n        \n        save_kwargs = {\n            \"quality\": quality,\n            \"optimize\": self.config.optimize,\n        }\n        \n        if format.upper() == \"JPEG\":\n            save_kwargs[\"subsampling\"] = 0\n        \n        image.save(output_path, format=format, **save_kwargs)\n    \n    def save_to_bytes(\n        self,\n        image: Image,\n        format: str = None,\n        quality: int = None\n    ) -> bytes:\n        \"\"\"Save image to bytes.\"\"\"\n        format = format or self.config.format\n        quality = quality or self.config.quality\n        \n        buffer = io.BytesIO()\n        \n        save_kwargs = {\n            \"quality\": quality,\n            \"optimize\": self.config.optimize,\n        }\n        \n        image.save(buffer, format=format, **save_kwargs)\n        \n        return buffer.getvalue()\n    \n    def create_responsive_set(\n        self,\n        image: Image,\n        sizes: List[Tuple[int, str]],\n        output_dir: Path,\n        prefix: str = \"image\"\n    ) -> List[dict]:\n        \"\"\"Create responsive image set.\"\"\"\n        results = []\n        \n        for width, suffix in sizes:\n            new_height = int(image.height * (width \u002F image.width))\n            \n            resized = self.resize(\n                image,\n                width,\n                new_height,\n                maintain_aspect=True\n            )\n            \n            filename = f\"{prefix}_{suffix}.jpg\"\n            output_path = output_dir \u002F filename\n            \n            self.save_with_quality(resized, output_path)\n            \n            results.append({\n                \"filename\": filename,\n                \"width\": resized.width,\n                \"height\": resized.height,\n                \"url\": f\"\u002Fimages\u002F{filename}\"\n            })\n        \n        return results\n```\n\n## Image Upload Handling\n```python\nfrom pathlib import Path\nfrom typing import Optional\nimport magic\nimport hashlib\n\n\nclass SecureImageUploader:\n    \"\"\"Secure image upload handling.\"\"\"\n    \n    ALLOWED_TYPES = {\n        \"image\u002Fjpeg\": \".jpg\",\n        \"image\u002Fpng\": \".png\",\n        \"image\u002Fgif\": \".gif\",\n        \"image\u002Fwebp\": \".webp\",\n    }\n    MAX_SIZE = 10 * 1024 * 1024  # 10MB\n    \n    def __init__(self, upload_dir: Path, processor: ImageProcessor):\n        self.upload_dir = upload_dir\n        self.processor = processor\n        self.upload_dir.mkdir(parents=True, exist_ok=True)\n    \n    async def save_upload(\n        self,\n        file_content: bytes,\n        original_filename: str\n    ) -> dict:\n        \"\"\"Save uploaded image securely.\"\"\"\n        # Validate file type\n        mime_type = magic.from_buffer(file_content, mime=True)\n        \n        if mime_type not in self.ALLOWED_TYPES:\n            raise InvalidImageError(\n                f\"Invalid file type: {mime_type}\"\n            )\n        \n        # Validate size\n        if len(file_content) > self.MAX_SIZE:\n            raise InvalidImageError(\n                f\"File too large: {len(file_content)} bytes\"\n            )\n        \n        # Generate safe filename\n        ext = self.ALLOWED_TYPES[mime_type]\n        safe_filename = self._generate_safe_filename(original_filename, ext)\n        file_path = self.upload_dir \u002F safe_filename\n        \n        # Save file\n        file_path.write_bytes(file_content)\n        \n        # Process image\n        image = self.processor.open(file_path)\n        \n        # Create thumbnail\n        thumbnail = self.processor.create_thumbnail(image)\n        thumbnail_path = self.upload_dir \u002F f\"thumb_{safe_filename}\"\n        self.processor.save_with_quality(thumbnail, thumbnail_path)\n        \n        return {\n            \"original\": str(file_path),\n            \"thumbnail\": str(thumbnail_path),\n            \"filename\": safe_filename,\n            \"width\": image.width,\n            \"height\": image.height,\n            \"size\": len(file_content),\n            \"type\": mime_type,\n        }\n    \n    def _generate_safe_filename(\n        self,\n        original_filename: str,\n        extension: str\n    ) -> str:\n        \"\"\"Generate safe, unique filename.\"\"\"\n        # Get base name\n        stem = Path(original_filename).stem\n        \n        # Sanitize\n        safe_stem = \"\".join(\n            c for c in stem\n            if c.isalnum() or c in \"-_\"\n        )\n        safe_stem = safe_stem[:50]  # Limit length\n        \n        # Add hash for uniqueness\n        hash_suffix = hashlib.md5(\n            f\"{original_filename}{datetime.utcnow().isoformat()}\".encode()\n        ).hexdigest()[:8]\n        \n        return f\"{safe_stem}_{hash_suffix}{extension}\"\n```\n\n## Image Analysis\n```python\nfrom PIL import ImageDraw, ImageFont\nfrom collections import Counter\n\n\nclass ImageAnalyzer:\n    \"\"\"Analyze image properties.\"\"\"\n    \n    @staticmethod\n    def get_dimensions(image: Image) -> Tuple[int, int]:\n        \"\"\"Get image dimensions.\"\"\"\n        return image.width, image.height\n    \n    @staticmethod\n    def get_format(image: Image) -> str:\n        \"\"\"Get image format.\"\"\"\n        return image.format or \"Unknown\"\n    \n    @staticmethod\n    def get_mode(image: Image) -> str:\n        \"\"\"Get image mode (RGB, L, etc.).\"\"\"\n        return image.mode\n    \n    @staticmethod\n    def get_info(image: Image) -> dict:\n        \"\"\"Get comprehensive image info.\"\"\"\n        return {\n            \"format\": image.format,\n            \"mode\": image.mode,\n            \"width\": image.width,\n            \"height\": image.height,\n            \"size_bytes\": image.size[0] * image.size[1],\n            \"has_alpha\": image.mode in (\"RGBA\", \"LA\", \"P\"),\n            \"aspect_ratio\": image.width \u002F image.height if image.height else 0,\n        }\n    \n    @staticmethod\n    def get_color_histogram(image: Image) -> dict:\n        \"\"\"Get color histogram.\"\"\"\n        if image.mode != \"RGB\":\n            image = image.convert(\"RGB\")\n        \n        colors = list(image.getdata())\n        color_counts = Counter(colors)\n        \n        return {\n            \"unique_colors\": len(color_counts),\n            \"top_colors\": color_counts.most_common(10),\n        }\n    \n    @staticmethod\n    def is_portrait(image: Image) -> bool:\n        \"\"\"Check if image is portrait orientation.\"\"\"\n        return image.height > image.width\n    \n    @staticmethod\n    def is_landscape(image: Image) -> bool:\n        \"\"\"Check if image is landscape orientation.\"\"\"\n        return image.width > image.height\n    \n    @staticmethod\n    def is_square(image: Image) -> bool:\n        \"\"\"Check if image is square.\"\"\"\n        return image.width == image.height\n    \n    @staticmethod\n    def estimate_quality(image: Image) -> str:\n        \"\"\"Estimate image quality level.\"\"\"\n        width = image.width\n        height = image.height\n        \n        if width \u003C 300 or height \u003C 300:\n            return \"low\"\n        elif width \u003C 800 or height \u003C 800:\n            return \"medium\"\n        elif width \u003C 2000 or height \u003C 2000:\n            return \"high\"\n        else:\n            return \"very_high\"\n\n\n# Watermark application\nclass WatermarkApplier:\n    \"\"\"Apply watermarks to images.\"\"\"\n    \n    def __init__(self, text: str, font_size: int = 24):\n        self.text = text\n        self.font_size = font_size\n    \n    def add_text_watermark(\n        self,\n        image: Image,\n        position: str = \"bottom-right\",\n        opacity: float = 0.5\n    ) -> Image:\n        \"\"\"Add text watermark.\"\"\"\n        if image.mode != \"RGBA\":\n            image = image.convert(\"RGBA\")\n        \n        watermark = Image.new(\"RGBA\", image.size, (255, 255, 255, 0))\n        draw = ImageDraw.Draw(watermark)\n        \n        # Calculate position\n        width, height = image.size\n        \n        if position == \"bottom-right\":\n            x = width - 200\n            y = height - 50\n        elif position == \"bottom-left\":\n            x = 20\n            y = height - 50\n        elif position == \"top-right\":\n            x = width - 200\n            y = 20\n        elif position == \"top-left\":\n            x = 20\n            y = 20\n        else:  # center\n            x = width \u002F\u002F 2 - 50\n            y = height \u002F\u002F 2\n        \n        # Draw text with transparency\n        draw.text(\n            (x, y),\n            self.text,\n            fill=(255, 255, 255, int(255 * opacity))\n        )\n        \n        # Composite\n        watermarked = Image.alpha_composite(image, watermark)\n        \n        return watermarked.convert(\"RGB\")\n```\n\n## Best Practices\n```\nImage Processing Best Practices:\n\n1. Validate uploads\n   Check file type\n   Check file size\n\n2. Generate unique names\n   Prevent overwrites\n   Use hashes\n\n3. Create thumbnails\n   For previews\n   Reduce bandwidth\n\n4. Use appropriate formats\n   JPEG for photos\n   PNG for graphics\n   WebP for modern browsers\n\n5. Optimize for web\n   Compress images\n   Right-size dimensions\n\n6. Preserve aspect ratio\n   Don't distort images\n   Calculate dimensions\n\n7. Handle metadata\n   Strip sensitive EXIF\n   Preserve copyright if needed\n\n8. Serve efficiently\n   CDN for delivery\n   Responsive images\n\n9. Process asynchronously\n   Don't block requests\n   Use queues\n\n10. Clean up old files\n    Define retention\n    Delete unused images\n```\n","## What I do\n- Resize and transform images\n- Handle image formats\n- Optimize image quality\n- Generate thumbnails\n- Extract image metadata\n- Apply filters and effects\n- Handle image uploads securely\n- Serve optimized images\n\n## When to use me\nWhen implementing image processing or handling image uploads.\n\n## Image Processing Basics\n```python\nfrom PIL import Image, ImageFilter, ImageEnhance\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Optional, List, Tuple\nimport io\n\n\n@dataclass\nclass ImageDimensions:\n    \"\"\"Image dimensions.\"\"\"\n    width: int\n    height: int\n    \n    @property\n    def aspect_ratio(self) -> float:\n        return self.width \u002F self.height\n    \n    def resize(self, max_width: int, max_height: int) -> 'ImageDimensions':\n        \"\"\"Resize while maintaining aspect ratio.\"\"\"\n        ratio = min(max_width \u002F self.width, max_height \u002F self.height)\n        return ImageDimensions(\n            width=int(self.width * ratio),\n            height=int(self.height * ratio)\n        )\n\n\n@dataclass\nclass ImageConfig:\n    \"\"\"Image processing configuration.\"\"\"\n    format: str = \"JPEG\"\n    quality: int = 85\n    optimize: bool = True\n    preserve_metadata: bool = False\n\n\nclass ImageProcessor:\n    \"\"\"Image processing operations.\"\"\"\n    \n    def __init__(self, config: ImageConfig = None):\n        self.config = config or ImageConfig()\n    \n    def open(self, image_path: Path) -> Image:\n        \"\"\"Open an image file.\"\"\"\n        return Image.open(image_path)\n    \n    def resize(\n        self,\n        image: Image,\n        width: int,\n        height: int,\n        maintain_aspect: bool = True\n    ) -> Image:\n        \"\"\"Resize image.\"\"\"\n        if maintain_aspect:\n            current_dims = ImageDimensions(image.width, image.height)\n            new_dims = current_dims.resize(width, height)\n            width, height = new_dims.width, new_dims.height\n        \n        return image.resize((width, height), Image.LANCZOS)\n    \n    def create_thumbnail(\n        self,\n        image: Image,\n        max_size: Tuple[int, int] = (300, 300)\n    ) -> Image:\n        \"\"\"Create thumbnail preserving aspect ratio.\"\"\"\n        image.thumbnail(max_size, Image.LANCZOS)\n        return image\n    \n    def crop(\n        self,\n        image: Image,\n        left: int,\n        top: int,\n        right: int,\n        bottom: int\n    ) -> Image:\n        \"\"\"Crop image.\"\"\"\n        return image.crop((left, top, right, bottom))\n    \n    def rotate(self, image: Image, degrees: float) -> Image:\n        \"\"\"Rotate image.\"\"\"\n        return image.rotate(-degrees, expand=True)\n    \n    def flip_horizontal(self, image: Image) -> Image:\n        \"\"\"Flip image horizontally.\"\"\"\n        return image.transpose(Image.FLIP_LEFT_RIGHT)\n    \n    def flip_vertical(self, image: Image) -> Image:\n        \"\"\"Flip image vertically.\"\"\"\n        return image.transpose(Image.FLIP_TOP_BOTTOM)\n\n\nclass ImageFilterApplier:\n    \"\"\"Apply filters to images.\"\"\"\n    \n    @staticmethod\n    def blur(image: Image, radius: float = 2) -> Image:\n        \"\"\"Apply Gaussian blur.\"\"\"\n        return image.filter(ImageFilter.GaussianBlur(radius))\n    \n    @staticmethod\n    def sharpen(image: Image) -> Image:\n        \"\"\"Sharpen image.\"\"\"\n        return image.filter(ImageFilter.SHARPEN)\n    \n    @staticmethod\n    def contour(image: Image) -> Image:\n        \"\"\"Apply contour filter.\"\"\"\n        return image.filter(ImageFilter.CONTOUR)\n    \n    @staticmethod\n    def edge_enhance(image: Image) -> Image:\n        \"\"\"Edge enhancement.\"\"\"\n        return image.filter(ImageFilter.EDGE_ENHANCE)\n    \n    @staticmethod\n    def emboss(image: Image) -> Image:\n        \"\"\"Apply emboss effect.\"\"\"\n        return image.filter(ImageFilter.EMBOSS)\n    \n    @staticmethod\n    def adjust_brightness(image: Image, factor: float) -> Image:\n        \"\"\"Adjust brightness.\"\"\"\n        enhancer = ImageEnhance.Brightness(image)\n        return enhancer.enhance(factor)\n    \n    @staticmethod\n    def adjust_contrast(image: Image, factor: float) -> Image:\n        \"\"\"Adjust contrast.\"\"\"\n        enhancer = ImageEnhance.Contrast(image)\n        return enhancer.enhance(factor)\n    \n    @staticmethod\n    def adjust_saturation(image: Image, factor: float) -> Image:\n        \"\"\"Adjust saturation.\"\"\"\n        enhancer = ImageEnhance.Color(image)\n        return enhancer.enhance(factor)\n\n\nclass ImageOptimizer:\n    \"\"\"Optimize images for web.\"\"\"\n    \n    def __init__(self, config: ImageConfig = None):\n        self.config = config or ImageConfig()\n    \n    def optimize(\n        self,\n        image: Image,\n        output_format: str = None\n    ) -> Image:\n        \"\"\"Optimize image.\"\"\"\n        format = output_format or self.config.format\n        \n        if format.upper() == \"JPEG\":\n            image = image.convert(\"RGB\")\n        \n        return image\n    \n    def save_with_quality(\n        self,\n        image: Image,\n        output_path: Path,\n        quality: int = None,\n        format: str = None\n    ) -> None:\n        \"\"\"Save image with specific quality.\"\"\"\n        quality = quality or self.config.quality\n        format = format or self.config.format\n        \n        save_kwargs = {\n            \"quality\": quality,\n            \"optimize\": self.config.optimize,\n        }\n        \n        if format.upper() == \"JPEG\":\n            save_kwargs[\"subsampling\"] = 0\n        \n        image.save(output_path, format=format, **save_kwargs)\n    \n    def save_to_bytes(\n        self,\n        image: Image,\n        format: str = None,\n        quality: int = None\n    ) -> bytes:\n        \"\"\"Save image to bytes.\"\"\"\n        format = format or self.config.format\n        quality = quality or self.config.quality\n        \n        buffer = io.BytesIO()\n        \n        save_kwargs = {\n            \"quality\": quality,\n            \"optimize\": self.config.optimize,\n        }\n        \n        image.save(buffer, format=format, **save_kwargs)\n        \n        return buffer.getvalue()\n    \n    def create_responsive_set(\n        self,\n        image: Image,\n        sizes: List[Tuple[int, str]],\n        output_dir: Path,\n        prefix: str = \"image\"\n    ) -> List[dict]:\n        \"\"\"Create responsive image set.\"\"\"\n        results = []\n        \n        for width, suffix in sizes:\n            new_height = int(image.height * (width \u002F image.width))\n            \n            resized = self.resize(\n                image,\n                width,\n                new_height,\n                maintain_aspect=True\n            )\n            \n            filename = f\"{prefix}_{suffix}.jpg\"\n            output_path = output_dir \u002F filename\n            \n            self.save_with_quality(resized, output_path)\n            \n            results.append({\n                \"filename\": filename,\n                \"width\": resized.width,\n                \"height\": resized.height,\n                \"url\": f\"\u002Fimages\u002F{filename}\"\n            })\n        \n        return results\n```\n\n## Image Upload Handling\n```python\nfrom pathlib import Path\nfrom typing import Optional\nimport magic\nimport hashlib\n\n\nclass SecureImageUploader:\n    \"\"\"Secure image upload handling.\"\"\"\n    \n    ALLOWED_TYPES = {\n        \"image\u002Fjpeg\": \".jpg\",\n        \"image\u002Fpng\": \".png\",\n        \"image\u002Fgif\": \".gif\",\n        \"image\u002Fwebp\": \".webp\",\n    }\n    MAX_SIZE = 10 * 1024 * 1024  # 10MB\n    \n    def __init__(self, upload_dir: Path, processor: ImageProcessor):\n        self.upload_dir = upload_dir\n        self.processor = processor\n        self.upload_dir.mkdir(parents=True, exist_ok=True)\n    \n    async def save_upload(\n        self,\n        file_content: bytes,\n        original_filename: str\n    ) -> dict:\n        \"\"\"Save uploaded image securely.\"\"\"\n        # Validate file type\n        mime_type = magic.from_buffer(file_content, mime=True)\n        \n        if mime_type not in self.ALLOWED_TYPES:\n            raise InvalidImageError(\n                f\"Invalid file type: {mime_type}\"\n            )\n        \n        # Validate size\n        if len(file_content) > self.MAX_SIZE:\n            raise InvalidImageError(\n                f\"File too large: {len(file_content)} bytes\"\n            )\n        \n        # Generate safe filename\n        ext = self.ALLOWED_TYPES[mime_type]\n        safe_filename = self._generate_safe_filename(original_filename, ext)\n        file_path = self.upload_dir \u002F safe_filename\n        \n        # Save file\n        file_path.write_bytes(file_content)\n        \n        # Process image\n        image = self.processor.open(file_path)\n        \n        # Create thumbnail\n        thumbnail = self.processor.create_thumbnail(image)\n        thumbnail_path = self.upload_dir \u002F f\"thumb_{safe_filename}\"\n        self.processor.save_with_quality(thumbnail, thumbnail_path)\n        \n        return {\n            \"original\": str(file_path),\n            \"thumbnail\": str(thumbnail_path),\n            \"filename\": safe_filename,\n            \"width\": image.width,\n            \"height\": image.height,\n            \"size\": len(file_content),\n            \"type\": mime_type,\n        }\n    \n    def _generate_safe_filename(\n        self,\n        original_filename: str,\n        extension: str\n    ) -> str:\n        \"\"\"Generate safe, unique filename.\"\"\"\n        # Get base name\n        stem = Path(original_filename).stem\n        \n        # Sanitize\n        safe_stem = \"\".join(\n            c for c in stem\n            if c.isalnum() or c in \"-_\"\n        )\n        safe_stem = safe_stem[:50]  # Limit length\n        \n        # Add hash for uniqueness\n        hash_suffix = hashlib.md5(\n            f\"{original_filename}{datetime.utcnow().isoformat()}\".encode()\n        ).hexdigest()[:8]\n        \n        return f\"{safe_stem}_{hash_suffix}{extension}\"\n```\n\n## Image Analysis\n```python\nfrom PIL import ImageDraw, ImageFont\nfrom collections import Counter\n\n\nclass ImageAnalyzer:\n    \"\"\"Analyze image properties.\"\"\"\n    \n    @staticmethod\n    def get_dimensions(image: Image) -> Tuple[int, int]:\n        \"\"\"Get image dimensions.\"\"\"\n        return image.width, image.height\n    \n    @staticmethod\n    def get_format(image: Image) -> str:\n        \"\"\"Get image format.\"\"\"\n        return image.format or \"Unknown\"\n    \n    @staticmethod\n    def get_mode(image: Image) -> str:\n        \"\"\"Get image mode (RGB, L, etc.).\"\"\"\n        return image.mode\n    \n    @staticmethod\n    def get_info(image: Image) -> dict:\n        \"\"\"Get comprehensive image info.\"\"\"\n        return {\n            \"format\": image.format,\n            \"mode\": image.mode,\n            \"width\": image.width,\n            \"height\": image.height,\n            \"size_bytes\": image.size[0] * image.size[1],\n            \"has_alpha\": image.mode in (\"RGBA\", \"LA\", \"P\"),\n            \"aspect_ratio\": image.width \u002F image.height if image.height else 0,\n        }\n    \n    @staticmethod\n    def get_color_histogram(image: Image) -> dict:\n        \"\"\"Get color histogram.\"\"\"\n        if image.mode != \"RGB\":\n            image = image.convert(\"RGB\")\n        \n        colors = list(image.getdata())\n        color_counts = Counter(colors)\n        \n        return {\n            \"unique_colors\": len(color_counts),\n            \"top_colors\": color_counts.most_common(10),\n        }\n    \n    @staticmethod\n    def is_portrait(image: Image) -> bool:\n        \"\"\"Check if image is portrait orientation.\"\"\"\n        return image.height > image.width\n    \n    @staticmethod\n    def is_landscape(image: Image) -> bool:\n        \"\"\"Check if image is landscape orientation.\"\"\"\n        return image.width > image.height\n    \n    @staticmethod\n    def is_square(image: Image) -> bool:\n        \"\"\"Check if image is square.\"\"\"\n        return image.width == image.height\n    \n    @staticmethod\n    def estimate_quality(image: Image) -> str:\n        \"\"\"Estimate image quality level.\"\"\"\n        width = image.width\n        height = image.height\n        \n        if width \u003C 300 or height \u003C 300:\n            return \"low\"\n        elif width \u003C 800 or height \u003C 800:\n            return \"medium\"\n        elif width \u003C 2000 or height \u003C 2000:\n            return \"high\"\n        else:\n            return \"very_high\"\n\n\n# Watermark application\nclass WatermarkApplier:\n    \"\"\"Apply watermarks to images.\"\"\"\n    \n    def __init__(self, text: str, font_size: int = 24):\n        self.text = text\n        self.font_size = font_size\n    \n    def add_text_watermark(\n        self,\n        image: Image,\n        position: str = \"bottom-right\",\n        opacity: float = 0.5\n    ) -> Image:\n        \"\"\"Add text watermark.\"\"\"\n        if image.mode != \"RGBA\":\n            image = image.convert(\"RGBA\")\n        \n        watermark = Image.new(\"RGBA\", image.size, (255, 255, 255, 0))\n        draw = ImageDraw.Draw(watermark)\n        \n        # Calculate position\n        width, height = image.size\n        \n        if position == \"bottom-right\":\n            x = width - 200\n            y = height - 50\n        elif position == \"bottom-left\":\n            x = 20\n            y = height - 50\n        elif position == \"top-right\":\n            x = width - 200\n            y = 20\n        elif position == \"top-left\":\n            x = 20\n            y = 20\n        else:  # center\n            x = width \u002F\u002F 2 - 50\n            y = height \u002F\u002F 2\n        \n        # Draw text with transparency\n        draw.text(\n            (x, y),\n            self.text,\n            fill=(255, 255, 255, int(255 * opacity))\n        )\n        \n        # Composite\n        watermarked = Image.alpha_composite(image, watermark)\n        \n        return watermarked.convert(\"RGB\")\n```\n\n## Best Practices\n```\nImage Processing Best Practices:\n\n1. Validate uploads\n   Check file type\n   Check file size\n\n2. Generate unique names\n   Prevent overwrites\n   Use hashes\n\n3. Create thumbnails\n   For previews\n   Reduce bandwidth\n\n4. Use appropriate formats\n   JPEG for photos\n   PNG for graphics\n   WebP for modern browsers\n\n5. Optimize for web\n   Compress images\n   Right-size dimensions\n\n6. Preserve aspect ratio\n   Don't distort images\n   Calculate dimensions\n\n7. Handle metadata\n   Strip sensitive EXIF\n   Preserve copyright if needed\n\n8. Serve efficiently\n   CDN for delivery\n   Responsive images\n\n9. Process asynchronously\n   Don't block requests\n   Use queues\n\n10. Clean up old files\n    Define retention\n    Delete unused images\n```\n",{"name":5,"license":15,"metadata":29,"description":7,"compatibility":22},{"audience":30,"category":31},"developers","utilities","main","2ea764e153842704d24a2e9aa4170441a7f03081",".opencode\u002Fskills\u002Fimage-processing","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito","https:\u002F\u002Fgithub.com\u002FNeuralBlitz","nuralnexus.org","Independent Multidisciplinary Researcher, Creative Producer, and AI Systems Architect\r\nAn independent creator and research-driven systems designer.","2026-11-12 03:13:05",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add NeuralBlitz\u002FMito --skill image-processing",{"tool":46,"command":47},"bunx","bunx skills add NeuralBlitz\u002FMito --skill image-processing",{"tool":49,"command":50},"pnpm","pnpm dlx skills add NeuralBlitz\u002FMito --skill image-processing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fimage-processing\u002FSKILL.md",true,[],[55,71,84,97,105,120],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":24},"01M6HAZSAQK1S27CEZYAYJTQDX","wireless-communications","Wireless systems, mobile networks, and 5G\u002F6G","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwireless-communications\u002FSKILL.md",[],[62,63,64,65,66,67,68,69,22,70],"communications","wireless communications","wireless","systems","engineering","networks","5G","students","mobile",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":24},"01M6HAZFX6E8NK3WZWDX5YCKYY","websockets","WebSocket implementation and best practices","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwebassembly\u002Fwebsockets\u002FSKILL.md",[],[73,78,79,80,22,81,82,83],"websocket implementation","time","implementation","real-time","websocket","best practices",{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":24},"01M6HAZ6DAXBQ7QHXXM1EM7715","vulnerability-auditing","Vulnerability assessment and auditing","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvulnerability-auditing\u002FSKILL.md",[],[91,92,93,94,22,95,96],"vulnerability","vulnerability auditing","security","vulnerability assessment","cybersecurity","assessment",{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":24},"01M6HAZ3FKF3CS9Z3J96RVE2ZE","vulnerability-assessment","Finding and assessing security vulnerabilities","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvue\u002Fvulnerability-assessment\u002FSKILL.md",[],[94,91,96,93,104,22],"vulnerabilities",{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":24},"01M6HAYSHM6HKRKEHFP0SGZQX7","vlsi-design","Very-Large-Scale Integration circuit design and semiconductor engineering","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvlsi-design\u002FSKILL.md",[],[112,113,114,115,116,66,117,22,118,69,119],"vlsi design","VLSI","design","hardware","integration","computer","scale","circuit",{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":24},"01M6HAYPQ30FFE2JXD7WQJ8R6C","unsupervised","Unsupervised learning concepts","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvisualization\u002Funsupervised\u002FSKILL.md",[],[122,127,22,128,129,130,131,132],"learning","intelligence","unsupervised learning","machine","concepts","machine-learning"]