// ── จัดการทิศทางภาพ (auto-orient) ───────────────────────────── // เป้าหมาย: รูปที่ถ่าย/แชร์ออกไปต้องตั้งตรงทุกแอป แม้แอปปลายทางไม่สนใจ EXIF // วิธี: อ่าน EXIF Orientation → หมุนพิกเซลให้ตรง → เขียน Orientation = 1 กลับ import { JPEG_QUALITY, THUMB_MAX, THUMB_QUALITY } from "./config.js"; import { blobToDataURL, dataURLToBlob } from "./exif.js"; /** ตาราง EXIF orientation 1-8 → การแปลงเพื่อให้ภาพตั้งตรง */ export const ORIENTATION_MATRIX = { 1: { rotate: 0, mirror: false }, 2: { rotate: 0, mirror: true }, 3: { rotate: 180, mirror: false }, 4: { rotate: 180, mirror: true }, 5: { rotate: 90, mirror: true }, 6: { rotate: 90, mirror: false }, 7: { rotate: 270, mirror: true }, 8: { rotate: 270, mirror: false }, }; /** อ่านค่า Orientation จาก JPEG โดยตรง (fallback ถ้า piexif ไม่มี) */ export function readOrientationTag(bytes) { try { const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); if (u8[0] !== 0xff || u8[1] !== 0xd8) return 1; let i = 2; while (i < u8.length - 4) { if (u8[i] !== 0xff) { i++; continue; } const marker = u8[i + 1]; const len = (u8[i + 2] << 8) | u8[i + 3]; if (marker === 0xe1 && u8[i + 4] === 0x45 && u8[i + 5] === 0x78) { const tiff = i + 10; const little = u8[tiff] === 0x49; const rd16 = (o) => (little ? u8[o] | (u8[o + 1] << 8) : (u8[o] << 8) | u8[o + 1]); const rd32 = (o) => (little ? u8[o] | (u8[o + 1] << 8) | (u8[o + 2] << 16) | (u8[o + 3] << 24) : (u8[o] << 24) | (u8[o + 1] << 16) | (u8[o + 2] << 8) | u8[o + 3]) >>> 0; const ifd0 = tiff + rd32(tiff + 4); const count = rd16(ifd0); for (let k = 0; k < count; k++) { const entry = ifd0 + 2 + k * 12; if (rd16(entry) === 0x0112) return rd16(entry + 8); } return 1; } i += 2 + len; } return 1; } catch { return 1; } } /** อ่านขนาดจริงจากหัวไฟล์ JPEG (SOF) — ใช้ตรวจว่าเบราว์เซอร์หมุนให้แล้วหรือยัง */ export async function jpegSize(blob) { try { const u8 = new Uint8Array(await blob.slice(0, 65536).arrayBuffer()); if (u8[0] !== 0xff || u8[1] !== 0xd8) return null; let i = 2; while (i < u8.length - 9) { if (u8[i] !== 0xff) { i++; continue; } const m = u8[i + 1]; if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) { return { h: (u8[i + 5] << 8) | u8[i + 6], w: (u8[i + 7] << 8) | u8[i + 8] }; } const len = (u8[i + 2] << 8) | u8[i + 3]; if (!len) return null; i += 2 + len; } return null; } catch { return null; } } /** หมุน/พลิกพิกเซลด้วย canvas */ export async function transformImage(blob, rotateDeg = 0, mirror = false) { const bmp = await createImageBitmap(blob, { imageOrientation: "none" }); const swap = Math.abs(rotateDeg) % 180 === 90; const w = swap ? bmp.height : bmp.width; const h = swap ? bmp.width : bmp.height; const canvas = document.createElement("canvas"); canvas.width = w; canvas.height = h; const ctx = canvas.getContext("2d"); ctx.translate(w / 2, h / 2); ctx.rotate((rotateDeg * Math.PI) / 180); if (mirror) ctx.scale(-1, 1); ctx.drawImage(bmp, -bmp.width / 2, -bmp.height / 2); bmp.close?.(); const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY)); return { blob: out || blob, width: w, height: h, rotated: rotateDeg !== 0 || mirror }; } async function makeThumb(blob) { try { const bmp = await createImageBitmap(blob, { imageOrientation: "none" }); const scale = Math.min(1, THUMB_MAX / Math.max(bmp.width, bmp.height)); const w = Math.max(1, Math.round(bmp.width * scale)); const h = Math.max(1, Math.round(bmp.height * scale)); const canvas = document.createElement("canvas"); canvas.width = w; canvas.height = h; canvas.getContext("2d").drawImage(bmp, 0, 0, w, h); bmp.close?.(); return await new Promise((res) => canvas.toBlob(res, "image/jpeg", THUMB_QUALITY)); } catch { return blob; } } /** * ปรับภาพให้ตั้งตรง * - exifOrientation: ค่าจาก readExif() (ถ้ามี) * - mirrorFront: true = กล้องหน้า → พลิกซ้าย-ขวาให้เหมือนพรีวิว (ค่าเริ่มต้น false) * คืน { blob, width, height, rotation, mirrored, source } */ export async function autoOrient({ blob, exifOrientation = 1, width, height, mirrorFront = false, facing = "environment" }) { const tag = ORIENTATION_MATRIX[exifOrientation] ? exifOrientation : 1; const plan = ORIENTATION_MATRIX[tag]; // กล้องหน้า: พรีวิวถูก mirror แต่ไฟล์ดิบไม่ mirror → พลิกให้ตรงกับที่เห็น const mirror = plan.mirror || (mirrorFront && facing === "user"); const rotate = plan.rotate; if (!rotate && !mirror) { return { blob, width: width || 0, height: height || 0, rotation: 0, mirrored: false, source: "none" }; } // เบราว์เซอร์หมุนตาม EXIF ให้เองหรือไม่ (Chrome/Android = ใช่) — ตรวจครั้งเดียวแล้ว cache if (await browserAppliesExif()) { const probe = await createImageBitmap(blob); const pw = probe.width, ph = probe.height; probe.close?.(); const baked = await bakeToJpeg(blob); if (mirror) { const flipped = await transformImage(baked, 0, true); return { ...flipped, width: pw, height: ph, rotation: 0, mirrored: true, source: `browser:${tag}+mirror` }; } return { blob: baked, width: pw, height: ph, rotation: 0, mirrored: false, source: `browser:${tag}` }; } // เบราว์เซอร์ไม่สนใจ EXIF → หมุนพิกเซลเองตามตาราง const out = await transformImage(blob, rotate, mirror); return { ...out, rotation: rotate, mirrored: mirror, source: `exif:${tag}${mirrorFront && facing === "user" ? "+front" : ""}`, }; } let _exifSupport = null; /** ทดสอบว่า createImageBitmap หมุนตาม EXIF ให้หรือไม่ (cache ผลไว้) */ async function browserAppliesExif() { if (_exifSupport !== null) return _exifSupport; try { const px = window.piexif; if (!px) { _exifSupport = true; return true; } const c = document.createElement("canvas"); c.width = 40; c.height = 20; c.getContext("2d").fillRect(0, 0, 40, 20); const plain = await new Promise((r) => c.toBlob(r, "image/jpeg", 0.9)); const durl = await blobToDataURL(plain); const raw = px.load(durl); raw["0th"][274] = 6; const tagged = dataURLToBlob(px.insert(px.dump(raw), durl)); const bmp = await createImageBitmap(tagged); _exifSupport = bmp.width === 20 && bmp.height === 40; bmp.close?.(); } catch { _exifSupport = true; } return _exifSupport; } /** วาดภาพตามที่เบราว์เซอร์แสดง (bake) แล้วคืน JPEG ที่ไม่มี EXIF */ async function bakeToJpeg(blob) { const bmp = await createImageBitmap(blob); const canvas = document.createElement("canvas"); canvas.width = bmp.width; canvas.height = bmp.height; canvas.getContext("2d").drawImage(bmp, 0, 0); bmp.close?.(); const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY)); return out || blob; } /** ครอปกลางภาพตามอัตราส่วน (4:3 = 1.333, 3:4 = 0.75) */ export async function cropToRatio(blob, ratio) { try { const bmp = await createImageBitmap(blob, { imageOrientation: "none" }); const w = bmp.width, h = bmp.height; const src = w / h; let sw = w, sh = h, sx = 0, sy = 0; if (src > ratio + 0.002) { sw = Math.round(h * ratio); sx = Math.round((w - sw) / 2); } else if (src < ratio - 0.002) { sh = Math.round(w / ratio); sy = Math.round((h - sh) / 2); } if (sw === w && sh === h) { bmp.close?.(); return { blob, width: w, height: h }; } const canvas = document.createElement("canvas"); canvas.width = sw; canvas.height = sh; canvas.getContext("2d").drawImage(bmp, sx, sy, sw, sh, 0, 0, sw, sh); bmp.close?.(); const out = await new Promise((res) => canvas.toBlob(res, "image/jpeg", JPEG_QUALITY)); return { blob: out || blob, width: sw, height: sh }; } catch { return { blob, width: 0, height: 0 }; } } /** "4:3" → 1.333 */ export function ratioValue(label) { const m = /^(\d+)\s*[:x/]\s*(\d+)$/.exec(String(label || "")); if (!m) return 4 / 3; const a = Number(m[1]), b = Number(m[2]); return b ? a / b : 4 / 3; } /** หมุนภาพตามองศา (ใช้กับปุ่มหมุนในชีตรูป) และสร้าง thumb ใหม่ */ export async function rotateBlob(blob, deg) { const out = await transformImage(blob, deg, false); const thumb = await makeThumb(out.blob); return { ...out, thumb }; } /** อ่าน orientation จาก blob แล้วคืนค่าตัวเลข 1-8 */ export async function detectOrientation(blob) { try { const buf = await blob.arrayBuffer(); return readOrientationTag(new Uint8Array(buf)); } catch { return 1; } } export { makeThumb as makeThumbFromBlob };