// ── อ่าน/เขียน EXIF (JPEG) ด้วย piexifjs ───────────────────── // เป้าหมาย: metadata อยู่ใน "ไฟล์รูป" แบบเดียวกับแอปกล้องของ Samsung // (Make/Model/เวลา/GPS/ความละเอียด ฯลฯ ฝังใน EXIF — ไม่มีไฟล์ JSON แยก) const piexif = () => (typeof window !== "undefined" ? window.piexif : undefined); export function blobToDataURL(blob) { return new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(r.result); r.onerror = () => reject(r.error); r.readAsDataURL(blob); }); } export function dataURLToBlob(dataUrl) { const [head, b64] = dataUrl.split(","); const mime = /:(.*?);/.exec(head)?.[1] || "image/jpeg"; const bin = atob(b64); const bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); return new Blob([bytes], { type: mime }); } const rat = (v) => { if (Array.isArray(v) && v.length === 2) return v[1] ? v[0] / v[1] : 0; return typeof v === "number" ? v : 0; }; const dmsToDecimal = (dms, ref) => { if (!Array.isArray(dms) || dms.length < 3) return null; const deg = rat(dms[0]) + rat(dms[1]) / 60 + rat(dms[2]) / 3600; const v = Number(deg.toFixed(6)); return ref === "S" || ref === "W" ? -v : v; }; const str = (v) => { if (typeof v !== "string") return undefined; const s = v.replace(/\0+$/, "").trim(); return s || undefined; }; /** อ่าน EXIF จาก JPEG → object แบน (คีย์ไม่มี = ไฟล์ไม่มี tag นั้น) */ export async function readExif(blob) { const px = piexif(); if (!px || !blob) return {}; try { const dataUrl = await blobToDataURL(blob); if (!dataUrl.startsWith("data:image/jpeg")) return {}; const exif = px.load(dataUrl) || {}; const o = exif["0th"] || {}; const e = exif.Exif || {}; const g = exif.GPS || {}; return { make: str(o[271]), model: str(o[272]), description: str(o[270]), software: str(o[305]), dateTime: str(o[306]), dateTimeOriginal: str(e[36867]), dateTimeDigitized: str(e[36868]), orientation: typeof o[274] === "number" ? o[274] : undefined, xResolution: o[282] ? rat(o[282]) : undefined, resolutionUnit: o[296], colorSpace: e[40961], exifVersion: str(e[36864]), uniqueId: str(e[42016]), width: e[40962] || o[256] || undefined, height: e[40963] || o[257] || undefined, iso: typeof e[34855] === "number" ? e[34855] : undefined, fNumber: e[33437] ? rat(e[33437]) : undefined, exposureTime: e[33434] ? rat(e[33434]) : undefined, exposureBias: e[37380] ? rat(e[37380]) : undefined, focalLength: e[37386] ? rat(e[37386]) : undefined, lensModel: str(e[42036]), lensMake: str(e[42035]), hasMakerNote: !!e[37500], xpComment: fromUtf16le(o[40092]), xpKeywords: fromUtf16le(o[40094]), gps: g[2] ? { lat: dmsToDecimal(g[2], str(g[1])), lng: dmsToDecimal(g[4], str(g[3])), altitude: g[6] ? rat(g[6]) * (str(g[5]) === "1" ? -1 : 1) : null, accuracy: g[31] ? rat(g[31]) : null, dateStamp: str(g[29]), timeStamp: Array.isArray(g[7]) ? g[7].map(rat) : null, processingMethod: str(g[27]), } : null, }; } catch { return {}; } } /** ตัดอักษรนอก ASCII ออกให้หมด (ใช้กับชื่อที่ต้องอ่านรู้เรื่อง) */ const asciiStripped = (s, fallback = "CamCat") => { const v = String(s ?? "").normalize("NFC").replace(/[^\x20-\x7E]/g, "").replace(/\s{2,}/g, " ").trim(); return v || fallback; }; /** EXIF ASCII รับได้เฉพาะ Latin1 — แทนอักษรนอกช่วงด้วย ? (ชื่อไทยเก็บใน XPComment แทน) */ const ascii = (s, fallback = "") => { const v = String(s ?? "").normalize("NFC").replace(/[^\x20-\x7E]/g, "?").trim(); return v || fallback; }; /** XP* tags เก็บ Unicode แบบ UTF-16LE เป็น array ของ byte */ const utf16le = (s) => { const out = []; for (const ch of String(s ?? "")) { const code = ch.codePointAt(0); if (code > 0xffff) { const v = code - 0x10000; const hi = 0xd800 + (v >> 10); const lo = 0xdc00 + (v & 0x3ff); out.push(hi & 0xff, hi >> 8, lo & 0xff, lo >> 8); } else { out.push(code & 0xff, code >> 8); } } out.push(0, 0); // null terminator return out; }; const fromUtf16le = (bytes) => { if (!Array.isArray(bytes) || !bytes.length) return undefined; const codes = []; for (let i = 0; i + 1 < bytes.length; i += 2) { const c = bytes[i] | (bytes[i + 1] << 8); if (c === 0) break; codes.push(c); } if (!codes.length) return undefined; try { return String.fromCharCode(...codes); } catch { return undefined; } }; const decToDms = (dec) => { const abs = Math.abs(dec); const d = Math.floor(abs); const minFloat = (abs - d) * 60; const m = Math.floor(minFloat); const s = Math.round((minFloat - m) * 60 * 100); return [[d, 1], [m, 1], [s, 100]]; }; /** แยก "YYYY:MM:DD HH:MM:SS" เพื่อใช้กับ GPSTimeStamp/GPSDateStamp */ function splitDateTime(dateTime) { const m = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(dateTime || ""); if (!m) return null; return { date: `${m[1]}:${m[2]}:${m[3]}`, h: +m[4], mi: +m[5], s: +m[6] }; } /** * ฝัง EXIF มาตรฐานลง JPEG (แบบที่แอปกล้อง Samsung เขียน) * meta = { * make, model, modelName, software, dateTime, * width, height, folder, orientation, uniqueId, * gps: { lat, lng, altitude, accuracy }, * iso, fNumber, exposureTime, focalLength // ใส่เฉพาะที่มีค่าจริง * } * คืน Blob ใหม่ — ถ้าเขียนไม่ได้คืน blob เดิม */ export async function writeExif(blob, meta = {}) { const px = piexif(); if (!px || !blob || blob.type !== "image/jpeg") return blob; try { const dataUrl = await blobToDataURL(blob); let existing = {}; try { existing = px.load(dataUrl) || {}; } catch { existing = {}; } const zeroth = { ...(existing["0th"] || {}) }; const exif = { ...(existing.Exif || {}) }; const gps = { ...(existing.GPS || {}) }; // ── IFD0 (ASCII เท่านั้น) ── const fullLabel = meta.folder ? `CamCat · ${meta.folder}` : "CamCat"; zeroth[270] = asciiStripped(fullLabel, "CamCat"); // ImageDescription zeroth[271] = ascii(meta.make, "samsung"); // Make zeroth[272] = ascii(meta.model || meta.modelName, "CamCat Web"); // Model zeroth[305] = ascii(meta.software, "CamCat"); // Software zeroth[315] = asciiStripped(meta.folder || "CamCat", "CamCat"); // Artist = ชื่อโฟลเดอร์ // ชื่อที่มีอักษรไทย/Unicode → เก็บใน XPComment (UTF-16LE) และ XPKeywords if (/[^\x20-\x7E]/.test(String(meta.folder || ""))) { zeroth[40092] = utf16le(fullLabel); // XPComment zeroth[40094] = utf16le(meta.folder); // XPKeywords } if (meta.dateTime) zeroth[306] = meta.dateTime; zeroth[274] = meta.orientation || 1; // บังคับค่าหลัง normalize แล้ว zeroth[282] = [72, 1]; zeroth[283] = [72, 1]; zeroth[296] = 2; // นิ้ว // ── Exif IFD ── exif[36864] = "0232"; // ExifVersion (Undefined 4 ไบต์) if (meta.dateTime) { exif[36867] = meta.dateTime; // DateTimeOriginal exif[36868] = meta.dateTime; // DateTimeDigitized } exif[37121] = "\x01\x02\x03\x00"; // ComponentsConfiguration = YCbCr exif[40961] = 1; // ColorSpace = sRGB if (meta.width) exif[40962] = meta.width; if (meta.height) exif[40963] = meta.height; exif[37380] = [0, 1]; // ExposureBiasValue exif[41985] = 0; // CustomRendered: normal exif[41986] = 0; // ExposureMode: auto exif[41987] = 0; // WhiteBalance: auto exif[41988] = [1, 1]; // DigitalZoomRatio exif[41990] = 0; // SceneCaptureType: standard exif[41992] = 0; // Contrast: normal exif[41993] = 0; // Saturation: normal exif[41994] = 0; // Sharpness: normal if (meta.uniqueId) exif[42016] = ascii(meta.uniqueId).slice(0, 32); // ค่าที่วัดได้จริงเท่านั้น (ไม่เดา) if (Number.isFinite(meta.iso) && meta.iso > 0) exif[34855] = Math.round(meta.iso); if (Number.isFinite(meta.fNumber) && meta.fNumber > 0) exif[33437] = [Math.round(meta.fNumber * 10), 10]; if (Number.isFinite(meta.exposureTime) && meta.exposureTime > 0) { exif[33434] = meta.exposureTime >= 1 ? [Math.round(meta.exposureTime * 100), 100] : [1, Math.round(1 / meta.exposureTime)]; } if (Number.isFinite(meta.focalLength) && meta.focalLength > 0) exif[37386] = [Math.round(meta.focalLength * 10), 10]; if (meta.lensModel) exif[42036] = ascii(meta.lensModel); // ── GPS IFD ── const g = meta.gps; if (g && Number.isFinite(g.lat) && Number.isFinite(g.lng)) { const dt = splitDateTime(meta.dateTime); gps[0] = [2, 3, 0, 0]; gps[1] = g.lat >= 0 ? "N" : "S"; gps[2] = decToDms(g.lat); gps[3] = g.lng >= 0 ? "E" : "W"; gps[4] = decToDms(g.lng); if (Number.isFinite(g.altitude)) { gps[5] = g.altitude >= 0 ? 0 : 1; gps[6] = [Math.round(Math.abs(g.altitude) * 100), 100]; } if (Number.isFinite(g.accuracy) && g.accuracy > 0) { gps[31] = [Math.round(g.accuracy * 100), 100]; // GPSHPositioningError (เมตร) } if (dt) { gps[7] = [[dt.h, 1], [dt.mi, 1], [dt.s, 1]]; // GPSTimeStamp gps[29] = dt.date; // GPSDateStamp } gps[27] = "ASCII\x00\x00\x00GPS"; // GPSProcessingMethod } const dict = { "0th": zeroth, Exif: exif, GPS: gps, Interop: existing.Interop || {}, "1st": existing["1st"] || {}, thumbnail: existing.thumbnail || null, }; const inserted = px.insert(px.dump(dict), dataUrl); return dataURLToBlob(inserted); } catch (err) { console.warn("writeExif failed", err); return blob; } } /** "1/125 · f/1.8 · ISO 50 · 5mm" */ export function formatExposure(exif = {}) { const bits = []; if (exif.fNumber) bits.push("f/" + exif.fNumber.toFixed(1)); if (exif.exposureTime) bits.push(exif.exposureTime >= 1 ? exif.exposureTime.toFixed(1) + "s" : "1/" + Math.round(1 / exif.exposureTime) + "s"); if (exif.iso) bits.push("ISO " + exif.iso); if (exif.focalLength) bits.push(Math.round(exif.focalLength) + "mm"); return bits.join(" · "); }