"use client"; import React, { useState, useRef, useEffect } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Slider } from "@/components/ui/slider"; import { ImageIcon, Upload, Download, RefreshCw } from "lucide-react"; import { toast } from "sonner"; export default function ImageToPixelPage() { const [imageSrc, setImageSrc] = useState(null); const [pixelSize, setPixelSize] = useState(10); const canvasRef = useRef(null); const fileInputRef = useRef(null); const handleImageUpload = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (file) { const reader = new FileReader(); reader.onload = (event) => { setImageSrc(event.target?.result as string); }; reader.readAsDataURL(file); } }; useEffect(() => { if (imageSrc && canvasRef.current) { const canvas = canvasRef.current; const ctx = canvas.getContext("2d"); if (!ctx) return; const img = new Image(); img.src = imageSrc; img.onload = () => { // Setup canvas size canvas.width = img.width; canvas.height = img.height; // Draw original image ctx.drawImage(img, 0, 0); // Pixelate if (pixelSize > 1) { const w = canvas.width; const h = canvas.height; // Disable image smoothing for pixelation effect ctx.imageSmoothingEnabled = false; // Calculate smaller dimensions const sw = w / pixelSize; const sh = h / pixelSize; // Draw small image ctx.drawImage(canvas, 0, 0, w, h, 0, 0, sw, sh); // Draw back scaled up ctx.drawImage(canvas, 0, 0, sw, sh, 0, 0, w, h); } }; } }, [imageSrc, pixelSize]); const handleDownload = () => { if (canvasRef.current) { const link = document.createElement("a"); link.download = "pixel-art.png"; link.href = canvasRef.current.toDataURL(); link.click(); toast.success("图片已下载"); } }; return (

图片转像素画

将普通图片转换为像素艺术风格

{imageSrc ? (
) : (

请选择一张图片

支持 JPG, PNG, WEBP 格式

)}
调整与导出
setPixelSize(v[0])} min={1} max={50} step={1} disabled={!imageSrc} />

数值越大,像素颗粒感越强,画面越抽象。

); }