Files
photobooth/src/views/UploadView.vue

523 lines
15 KiB
Vue

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const uploadedPhotos = ref<string[]>([])
const fileInputRef = ref<HTMLInputElement>()
const totalPhotos = 4
const applyFilmEffect = (context: CanvasRenderingContext2D, width: number, height: number, volume: number = 5) => {
const imageData = context.getImageData(0, 0, width, height);
const data = imageData.data;
// 1. แปลง Volume (1-10) เป็นค่าที่ใช้งานได้จริง
// contrast: ยิ่งเยอะ ภาพยิ่งคมเข้ม (แนะนำช่วง 0 ถึง 50)
const contrast = (volume / 10) * 50;
const contrastFactor = (259 * (contrast + 255)) / (255 * (259 - contrast));
// tint: ปรับโทนสี (Film มักจะอมแดง/เขียว ลดฟ้า)
const redBoost = volume * 2; // เพิ่มแดงนิดหน่อย
const greenBoost = volume * 1; // เพิ่มเขียวจางๆ
const blueCut = volume * 3; // ลดฟ้าลงเพื่อให้ภาพดูอุ่น (Warm tone)
// grain: ความแรงของเม็ดเกรน
const grainStrength = volume * 1.5;
for (let i = 0; i < data.length; i += 4) {
let r = data[i];
let g = data[i + 1];
let b = data[i + 2];
// --- STEP 1: Apply Contrast (ทำให้ภาพไม่แบน) ---
// สูตร Contrast มาตรฐาน
r = contrastFactor * (r - 128) + 128;
g = contrastFactor * (g - 128) + 128;
b = contrastFactor * (b - 128) + 128;
// --- STEP 2: Color Grading (ปรับโทนฟิล์ม) ---
// ฟิล์ม Kodak/Fuji มักจะไม่ใช่ Sepia ล้วน แต่คือการจูน Channel
r += redBoost;
g += greenBoost;
b -= blueCut;
// --- STEP 3: Add Grain (เม็ดเกรน) ---
// ใช้เทคนิคสุ่มทั้งบวกและลบ เพื่อไม่ให้ความสว่างรวมเพี้ยน
const grain = (Math.random() - 0.5) * grainStrength;
// ผสมเกรนลงไป
r += grain;
g += grain;
b += grain;
// --- STEP 4: Clamp values (กันค่าเกิน 0-255) ---
// ถ้าไม่กันค่า จะเกิดจุดสีประหลาดๆ เมื่อค่าทะลุ 255 หรือต่ำกว่า 0
data[i] = Math.max(0, Math.min(255, r));
data[i + 1] = Math.max(0, Math.min(255, g));
data[i + 2] = Math.max(0, Math.min(255, b));
}
context.putImageData(imageData, 0, 0);
// --- STEP 5: (Optional) Add Vignette (ขอบมืด) ---
// การวาด Gradient ทับ เร็วกว่าและเนียนกว่าการคำนวณทีละ pixel
if (volume > 2) {
addVignette(context, width, height, volume);
}
};
// ฟังก์ชันเสริมสำหรับทำขอบมืด (Vignette)
const addVignette = (ctx: CanvasRenderingContext2D, w: number, h: number, strength: number) => {
const opacity = (strength / 10) * 0.6; // สูงสุดที่ 0.6 opacity
const radius = Math.max(w, h) * 0.8;
// สร้าง Gradient วงกลมจากตรงกลาง
const gradient = ctx.createRadialGradient(w/2, h/2, 0, w/2, h/2, radius);
gradient.addColorStop(0.5, "rgba(0,0,0,0)"); // ตรงกลางใส
gradient.addColorStop(1, `rgba(0,0,0,${opacity})`); // ขอบดำ
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, w, h);
};
const drawDateStamp = (context: CanvasRenderingContext2D, width: number, height: number) => {
const now = new Date();
// จัดรูปแบบวันที่แบบกล้องฟิล์ม (เช่น '98 1 25 หรือ 25 1 '98)
// ปีเอาแค่ 2 หลักท้าย
const year = now.getFullYear().toString().slice(-2);
const month = (now.getMonth() + 1).toString().padStart(2, '0'); // หรือจะใช้เลขเดียวแบบกล้องเก่าๆ ก็ได้
const day = now.getDate().toString().padStart(2, '0');
const dateString = `'${year} ${month} ${day}`; // รูปแบบ: '24 01 18
// ตั้งค่า Font (Digital-like)
// แนะนำให้หา Font ชื่อ 'Digital-7' หรือ 'DS-Digital' มาลงจะเหมือนมาก
// แต่ถ้าไม่มี ใช้ Arial หรือ Courier New ก็พอไหวครับ
const fontSize = height * 0.05; // ขนาด 5% ของความสูงภาพ
context.font = `bold ${fontSize}px "Courier New", monospace`;
// สีส้มอมแดง (Classic Date Stamp Color)
context.fillStyle = "#ff5e3a";
// เพิ่มเงาเรืองแสงนิดๆ ให้ดูเหมือนไฟ LED ที่ยิงลงฟิล์ม
context.shadowColor = "#ff0000";
context.shadowBlur = 10;
// ตำแหน่ง: มุมขวาล่าง
const paddingX = width * 0.05;
const paddingY = height * 0.03;
const x = width - context.measureText(dateString).width - paddingX;
const y = height - paddingY;
context.fillText(dateString, x, y);
// Reset shadow เพื่อไม่ให้กวนการวาดส่วนอื่น
context.shadowBlur = 0;
};
const cropImageTo34 = (imageSrc: string): Promise<string> => {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
if (!context) {
resolve(imageSrc);
return;
}
const imgWidth = img.width;
const imgHeight = img.height;
// คำนวณขนาดสำหรับ 3:4 aspect ratio
const targetAspectRatio = 3 / 4; // width:height = 3:4
let cropWidth, cropHeight, cropX, cropY;
if (imgWidth / imgHeight > targetAspectRatio) {
// ภาพกว้างกว่าที่ต้องการ - ครอบด้านข้าง
cropHeight = imgHeight;
cropWidth = imgHeight * targetAspectRatio;
cropX = (imgWidth - cropWidth) / 2;
cropY = 0;
} else {
// ภาพสูงกว่าที่ต้องการ - ครอบด้านบน/ล่าง
cropWidth = imgWidth;
cropHeight = imgWidth / targetAspectRatio;
cropX = 0;
cropY = (imgHeight - cropHeight) / 2;
}
// ตั้งค่าขนาด canvas เป็น 3:4 (360x480) - ลดขนาดเพื่อป้องกัน localStorage quota exceeded
const finalWidth = 360;
const finalHeight = 480;
canvas.width = finalWidth;
canvas.height = finalHeight;
// วาดภาพที่ครอบแล้วไปยัง canvas
context.drawImage(
img,
cropX,
cropY,
cropWidth,
cropHeight, // ตำแหน่งและขนาดที่ครอบจากภาพต้นฉบับ
0,
0,
finalWidth,
finalHeight // ตำแหน่งและขนาดใน canvas
);
// Apply film effect with adjustable volume
applyFilmEffect(context, finalWidth, finalHeight, 7); // Default volume = 5
drawDateStamp(context, finalWidth, finalHeight);
// แปลงเป็น base64 ด้วย quality 0.7 เพื่อลดขนาด
const croppedDataUrl = canvas.toDataURL('image/jpeg', 0.7);
resolve(croppedDataUrl);
};
img.src = imageSrc;
});
}
const triggerFileInput = () => {
fileInputRef.value?.click()
}
const handleFileSelect = async (event: Event) => {
const target = event.target as HTMLInputElement
const files = target.files
if (!files) return
// แปลงไฟล์เป็น base64 และครอบเป็น 3:4
for (const file of Array.from(files)) {
if (uploadedPhotos.value.length >= totalPhotos) break
const reader = new FileReader()
reader.onload = async (e) => {
const result = e.target?.result as string
if (result) {
// ครอบภาพให้เป็น 3:4 ก่อนเก็บ
const croppedImage = await cropImageTo34(result)
uploadedPhotos.value.push(croppedImage)
}
}
reader.readAsDataURL(file)
}
// เคลียร์ input
target.value = ''
}
const removePhoto = (index: number) => {
uploadedPhotos.value.splice(index, 1)
}
const proceedToNext = () => {
if (uploadedPhotos.value.length !== totalPhotos) {
alert(`กรุณาอัพโหลดภาพให้ครบ ${totalPhotos} รูป`)
return
}
try {
// เคลียร์ cached images ที่เก่าออกก่อนเพื่อให้มีพื้นที่
const keysToRemove = []
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (key && (key.startsWith('photobooth-1x4-') || key.startsWith('photobooth-2x2-'))) {
keysToRemove.push(key)
}
}
keysToRemove.forEach(key => localStorage.removeItem(key))
// เก็บรูปภาพไว้ใน localStorage
localStorage.setItem('photobooth-photos', JSON.stringify(uploadedPhotos.value))
router.push('/printstep')
} catch (error) {
if (error instanceof DOMException && error.name === 'QuotaExceededError') {
alert('รูปภาพมีขนาดใหญ่เกินไป กรุณาเลือกภาพขนาดเล็กลงหรือจำนวนน้อยลง')
console.error('localStorage quota exceeded:', error)
} else {
console.error('Error saving photos:', error)
alert('เกิดข้อผิดพลาดในการบันทึกภาพ')
}
}
}
const goBack = () => {
router.push('/selectsource')
}
</script>
<template>
<div class="upload-container">
<header class="header">
<button @click="goBack" class="back-button"> กล</button>
<h1>พโหลดภาพ</h1>
<span class="photo-counter">{{ uploadedPhotos.length }}/{{ totalPhotos }}</span>
</header>
<section class="upload-section">
<div class="upload-area" @click="triggerFileInput">
<div class="upload-icon">📁</div>
<h3>คลกเพอเลอกภาพ</h3>
<p>หรอลากและวางไฟลภาพลงท</p>
<p class="file-types">รองร: JPG, PNG, GIF</p>
</div>
<input
ref="fileInputRef"
type="file"
accept="image/*"
multiple
@change="handleFileSelect"
class="hidden-input"
/>
</section>
<section class="preview-section" v-if="uploadedPhotos.length > 0">
<h3>ภาพทเลอก</h3>
<div class="photo-grid">
<div
v-for="(photo, index) in uploadedPhotos"
:key="index"
class="photo-item"
>
<img :src="photo" :alt="`Uploaded photo ${index + 1}`" />
<button @click="removePhoto(index)" class="remove-button"></button>
<span class="photo-number">{{ index + 1 }}</span>
</div>
<!-- Placeholder สำหรบรปทงไมไดเลอก -->
<div
v-for="i in totalPhotos - uploadedPhotos.length"
:key="`placeholder-${i}`"
class="photo-placeholder"
@click="triggerFileInput"
>
<div class="placeholder-icon">+</div>
</div>
</div>
</section>
<section class="action-section" v-if="uploadedPhotos.length === totalPhotos">
<button @click="proceedToNext" class="next-button">
ดไป
</button>
</section>
</div>
</template>
<style scoped>
.upload-container {
min-height: 100vh;
padding: 2rem;
background: #f8f9fa;
display: flex;
flex-direction: column;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 2rem;
}
.back-button {
background: #6c757d;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 8px;
cursor: pointer;
font-size: 1rem;
}
.header h1 {
margin: 0;
color: #333;
font-size: 2rem;
}
.photo-counter {
background: #007bff;
color: white;
padding: 0.5rem 1rem;
border-radius: 20px;
font-weight: bold;
}
.upload-section {
margin-bottom: 2rem;
}
.upload-area {
background: white;
border: 2px dashed #dee2e6;
border-radius: 16px;
padding: 3rem 2rem;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
}
.upload-area:hover {
border-color: #007bff;
background: #f8f9ff;
}
.upload-icon {
font-size: 4rem;
margin-bottom: 1rem;
color: #6c757d;
}
.upload-area h3 {
margin: 0 0 0.5rem 0;
color: #333;
font-size: 1.5rem;
}
.upload-area p {
margin: 0.5rem 0;
color: #666;
}
.file-types {
font-size: 0.9rem;
color: #999;
}
.hidden-input {
display: none;
}
.preview-section {
flex: 1;
}
.preview-section h3 {
margin-bottom: 1rem;
color: #333;
text-align: center;
}
.photo-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 1rem;
margin-bottom: 2rem;
}
.photo-item, .photo-placeholder {
position: relative;
aspect-ratio: 3/4;
border-radius: 12px;
overflow: hidden;
cursor: pointer;
transition: all 0.3s ease;
}
.photo-item:hover {
transform: scale(1.02);
}
.photo-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.remove-button {
position: absolute;
top: 8px;
right: 8px;
background: rgba(220, 53, 69, 0.9);
color: white;
border: none;
width: 24px;
height: 24px;
border-radius: 50%;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8rem;
transition: all 0.3s ease;
}
.remove-button:hover {
background: rgba(220, 53, 69, 1);
transform: scale(1.1);
}
.photo-number {
position: absolute;
bottom: 8px;
left: 8px;
background: rgba(0,0,0,0.7);
color: white;
width: 24px;
height: 24px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8rem;
font-weight: bold;
}
.photo-placeholder {
background: #f8f9fa;
border: 2px dashed #dee2e6;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
.photo-placeholder:hover {
border-color: #007bff;
background: #f8f9ff;
}
.placeholder-icon {
font-size: 2rem;
color: #6c757d;
}
.action-section {
text-align: center;
margin-top: 2rem;
}
.next-button {
background: #28a745;
color: white;
border: none;
padding: 1rem 2rem;
font-size: 1.2rem;
font-weight: bold;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(40,167,69,0.3);
}
.next-button:hover {
background: #218838;
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(40,167,69,0.4);
}
@media (max-width: 768px) {
.photo-grid {
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
}
}
</style>