image-convert.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { applyExifOrientation } from "./exif-orientation.ts";
  2. import { loadPhoton } from "./photon.ts";
  3. /**
  4. * Convert image to PNG format for terminal display.
  5. * Kitty graphics protocol requires PNG format (f=100).
  6. */
  7. export async function convertToPng(
  8. base64Data: string,
  9. mimeType: string,
  10. ): Promise<{ data: string; mimeType: string } | null> {
  11. // Already PNG, no conversion needed
  12. if (mimeType === "image/png") {
  13. return { data: base64Data, mimeType };
  14. }
  15. const photon = await loadPhoton();
  16. if (!photon) {
  17. // Photon not available, can't convert
  18. return null;
  19. }
  20. try {
  21. const bytes = new Uint8Array(Buffer.from(base64Data, "base64"));
  22. const rawImage = photon.PhotonImage.new_from_byteslice(bytes);
  23. const image = applyExifOrientation(photon, rawImage, bytes);
  24. if (image !== rawImage) rawImage.free();
  25. try {
  26. const pngBuffer = image.get_bytes();
  27. return {
  28. data: Buffer.from(pngBuffer).toString("base64"),
  29. mimeType: "image/png",
  30. };
  31. } finally {
  32. image.free();
  33. }
  34. } catch {
  35. // Conversion failed
  36. return null;
  37. }
  38. }