fix: handle multi-channel TIFF formats and add compression options

Add PDF quality selector (high/medium/low) with JPEG compression.
This commit is contained in:
alam00000
2026-04-04 13:09:22 +05:30
parent 12677f1647
commit 4efab56e48
4 changed files with 509 additions and 158 deletions

View File

@@ -1,8 +1,13 @@
import { showLoader, hideLoader, showAlert } from '../ui.js';
import { downloadFile, formatBytes, readFileAsArrayBuffer } from '../utils/helpers.js';
import {
downloadFile,
formatBytes,
readFileAsArrayBuffer,
} from '../utils/helpers.js';
import { createIcons, icons } from 'lucide';
import { PDFDocument as PDFLibDocument } from 'pdf-lib';
import { decode } from 'tiff';
import { tiffIfdToRgba } from '../utils/tiff-utils.js';
let files: File[] = [];
@@ -11,6 +16,8 @@ const updateUI = () => {
const fileControls = document.getElementById('file-controls');
const processBtn = document.getElementById('process-btn');
const optionsPanel = document.getElementById('tiff-options');
if (!fileDisplayArea || !fileControls || !processBtn) return;
fileDisplayArea.innerHTML = '';
@@ -18,10 +25,12 @@ const updateUI = () => {
if (files.length > 0) {
fileControls.classList.remove('hidden');
processBtn.classList.remove('hidden');
optionsPanel?.classList.remove('hidden');
files.forEach((file, index) => {
const fileDiv = document.createElement('div');
fileDiv.className = 'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
fileDiv.className =
'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
const infoContainer = document.createElement('div');
infoContainer.className = 'flex items-center gap-2 overflow-hidden';
@@ -37,7 +46,8 @@ const updateUI = () => {
infoContainer.append(nameSpan, sizeSpan);
const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.className =
'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
removeBtn.onclick = () => {
files = files.filter((_, i) => i !== index);
@@ -51,6 +61,7 @@ const updateUI = () => {
} else {
fileControls.classList.add('hidden');
processBtn.classList.add('hidden');
optionsPanel?.classList.add('hidden');
}
};
@@ -64,6 +75,18 @@ async function convert() {
showAlert('No Files', 'Please select at least one TIFF file.');
return;
}
const qualitySelect = document.getElementById(
'tiff-pdf-quality'
) as HTMLSelectElement;
const quality = qualitySelect?.value || 'medium';
const jpegQualityMap: Record<string, number> = {
high: 0.92,
medium: 0.75,
low: 0.5,
};
const useJpeg = quality !== 'high';
const jpegQuality = jpegQualityMap[quality] || 0.75;
showLoader('Converting TIFF to PDF...');
try {
const pdfDoc = await PDFLibDocument.create();
@@ -74,7 +97,6 @@ async function convert() {
for (const ifd of ifds) {
const width = ifd.width;
const height = ifd.height;
const rgba = ifd.data;
const canvas = document.createElement('canvas');
canvas.width = width;
@@ -82,25 +104,39 @@ async function convert() {
const ctx = canvas.getContext('2d');
if (!ctx) continue;
const rgba = tiffIfdToRgba(
ifd.data,
width,
height,
ifd.samplesPerPixel || 1,
ifd.type
);
const imageData = ctx.createImageData(width, height);
for (let i = 0; i < rgba.length; i++) {
imageData.data[i] = rgba[i];
}
imageData.data.set(rgba);
ctx.putImageData(imageData, 0, 0);
const pngBlob = await new Promise<Blob | null>((res) =>
canvas.toBlob(res, 'image/png')
const blob = await new Promise<Blob | null>((res) =>
canvas.toBlob(
res,
useJpeg ? 'image/jpeg' : 'image/png',
useJpeg ? jpegQuality : undefined
)
);
if (!pngBlob) continue;
if (!blob) continue;
const pngBytes = await pngBlob.arrayBuffer();
const pngImage = await pdfDoc.embedPng(pngBytes);
const page = pdfDoc.addPage([pngImage.width, pngImage.height]);
page.drawImage(pngImage, {
canvas.width = 0;
canvas.height = 0;
const imgBytes = await blob.arrayBuffer();
const image = useJpeg
? await pdfDoc.embedJpg(imgBytes)
: await pdfDoc.embedPng(imgBytes);
const page = pdfDoc.addPage([image.width, image.height]);
page.drawImage(image, {
x: 0,
y: 0,
width: pngImage.width,
height: pngImage.height,
width: image.width,
height: image.height,
});
}
}
@@ -147,7 +183,10 @@ document.addEventListener('DOMContentLoaded', () => {
);
if (validFiles.length < newFiles.length) {
showAlert('Invalid Files', 'Some files were skipped. Only TIFF files are allowed.');
showAlert(
'Invalid Files',
'Some files were skipped. Only TIFF files are allowed.'
);
}
if (validFiles.length > 0) {

View File

@@ -0,0 +1,45 @@
type TiffDataArray = Uint8Array | Uint16Array | Float32Array | Float64Array;
export function tiffIfdToRgba(
src: TiffDataArray,
width: number,
height: number,
channels: number,
photometricType: number
): Uint8ClampedArray {
const totalPixels = width * height;
const dst = new Uint8ClampedArray(totalPixels * 4);
const isWhiteIsZero = photometricType === 0;
let maxVal = 255;
if (src instanceof Uint16Array) maxVal = 65535;
else if (src instanceof Float32Array || src instanceof Float64Array)
maxVal = 1;
const norm = (v: number) => {
if (maxVal === 255) return v;
if (maxVal === 1) return Math.round(Math.min(1, Math.max(0, v)) * 255);
return v >> 8;
};
for (let p = 0; p < totalPixels; p++) {
const si = p * channels;
const di = p * 4;
if (channels >= 3) {
dst[di] = norm(src[si]);
dst[di + 1] = norm(src[si + 1]);
dst[di + 2] = norm(src[si + 2]);
dst[di + 3] = channels >= 4 ? norm(src[si + 3]) : 255;
} else {
let gray = norm(src[si]);
if (isWhiteIsZero) gray = 255 - gray;
dst[di] = gray;
dst[di + 1] = gray;
dst[di + 2] = gray;
dst[di + 3] = channels === 2 ? norm(src[si + 1]) : 255;
}
}
return dst;
}

View File

@@ -179,6 +179,27 @@
<div id="file-display-area" class="mt-4 space-y-2"></div>
<div id="tiff-options" class="hidden mt-6">
<div class="mb-4">
<label
for="tiff-pdf-quality"
class="block mb-2 text-sm font-medium text-gray-300"
>PDF Quality</label
>
<select
id="tiff-pdf-quality"
class="w-full bg-gray-700 border border-gray-600 text-gray-200 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
>
<option value="high">High Quality (Larger file)</option>
<option value="medium" selected>Medium Quality (Balanced)</option>
<option value="low">Low Quality (Smaller file)</option>
</select>
<p class="mt-1 text-xs text-gray-400">
Controls image compression when embedding into PDF
</p>
</div>
</div>
<button id="process-btn" class="hidden btn-gradient w-full mt-6">
Convert to PDF
</button>

View File

@@ -0,0 +1,246 @@
import { describe, it, expect } from 'vitest';
import { tiffIfdToRgba } from '../js/utils/tiff-utils';
describe('tiffIfdToRgba', () => {
describe('RGB (3 channels)', () => {
it('converts RGB data to RGBA with full opacity', () => {
const src = new Uint8Array([255, 0, 0, 0, 255, 0, 0, 0, 255]);
const result = tiffIfdToRgba(src, 3, 1, 3, 2);
expect(Array.from(result)).toEqual([
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255,
]);
});
it('handles a 2x2 RGB image', () => {
const src = new Uint8Array([
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120,
]);
const result = tiffIfdToRgba(src, 2, 2, 3, 2);
expect(result.length).toBe(16);
expect(result[0]).toBe(10);
expect(result[1]).toBe(20);
expect(result[2]).toBe(30);
expect(result[3]).toBe(255);
expect(result[4]).toBe(40);
expect(result[5]).toBe(50);
expect(result[6]).toBe(60);
expect(result[7]).toBe(255);
});
});
describe('RGBA (4 channels)', () => {
it('copies all 4 channels directly', () => {
const src = new Uint8Array([255, 128, 64, 200, 0, 0, 0, 0]);
const result = tiffIfdToRgba(src, 2, 1, 4, 2);
expect(Array.from(result)).toEqual([255, 128, 64, 200, 0, 0, 0, 0]);
});
it('preserves alpha = 0 (fully transparent)', () => {
const src = new Uint8Array([100, 100, 100, 0]);
const result = tiffIfdToRgba(src, 1, 1, 4, 2);
expect(result[3]).toBe(0);
});
it('preserves alpha = 255 (fully opaque)', () => {
const src = new Uint8Array([100, 100, 100, 255]);
const result = tiffIfdToRgba(src, 1, 1, 4, 2);
expect(result[3]).toBe(255);
});
});
describe('Grayscale (1 channel)', () => {
it('expands grayscale to RGB with full opacity', () => {
const src = new Uint8Array([128]);
const result = tiffIfdToRgba(src, 1, 1, 1, 1);
expect(Array.from(result)).toEqual([128, 128, 128, 255]);
});
it('handles black pixel', () => {
const src = new Uint8Array([0]);
const result = tiffIfdToRgba(src, 1, 1, 1, 1);
expect(Array.from(result)).toEqual([0, 0, 0, 255]);
});
it('handles white pixel', () => {
const src = new Uint8Array([255]);
const result = tiffIfdToRgba(src, 1, 1, 1, 1);
expect(Array.from(result)).toEqual([255, 255, 255, 255]);
});
it('handles multiple grayscale pixels', () => {
const src = new Uint8Array([0, 128, 255]);
const result = tiffIfdToRgba(src, 3, 1, 1, 1);
expect(result.length).toBe(12);
expect(result[0]).toBe(0);
expect(result[4]).toBe(128);
expect(result[8]).toBe(255);
expect(result[3]).toBe(255);
expect(result[7]).toBe(255);
expect(result[11]).toBe(255);
});
});
describe('Grayscale + Alpha (2 channels)', () => {
it('expands grayscale and copies alpha', () => {
const src = new Uint8Array([200, 100]);
const result = tiffIfdToRgba(src, 1, 1, 2, 1);
expect(Array.from(result)).toEqual([200, 200, 200, 100]);
});
it('handles fully transparent grayscale', () => {
const src = new Uint8Array([255, 0]);
const result = tiffIfdToRgba(src, 1, 1, 2, 1);
expect(result[3]).toBe(0);
});
});
describe('WhiteIsZero (photometric type 0)', () => {
it('inverts grayscale values', () => {
const src = new Uint8Array([0]);
const result = tiffIfdToRgba(src, 1, 1, 1, 0);
expect(Array.from(result)).toEqual([255, 255, 255, 255]);
});
it('inverts mid-gray', () => {
const src = new Uint8Array([200]);
const result = tiffIfdToRgba(src, 1, 1, 1, 0);
expect(result[0]).toBe(55);
expect(result[1]).toBe(55);
expect(result[2]).toBe(55);
});
it('inverts white to black', () => {
const src = new Uint8Array([255]);
const result = tiffIfdToRgba(src, 1, 1, 1, 0);
expect(Array.from(result)).toEqual([0, 0, 0, 255]);
});
it('does not invert alpha in grayscale+alpha', () => {
const src = new Uint8Array([0, 128]);
const result = tiffIfdToRgba(src, 1, 1, 2, 0);
expect(result[0]).toBe(255);
expect(result[3]).toBe(128);
});
it('does not affect RGB images', () => {
const src = new Uint8Array([100, 150, 200]);
const result = tiffIfdToRgba(src, 1, 1, 3, 0);
expect(result[0]).toBe(100);
expect(result[1]).toBe(150);
expect(result[2]).toBe(200);
});
});
describe('16-bit images', () => {
it('normalizes 16-bit RGB to 8-bit', () => {
const src = new Uint16Array([65535, 0, 32768]);
const result = tiffIfdToRgba(src, 1, 1, 3, 2);
expect(result[0]).toBe(255);
expect(result[1]).toBe(0);
expect(result[2]).toBe(128);
expect(result[3]).toBe(255);
});
it('normalizes 16-bit grayscale to 8-bit', () => {
const src = new Uint16Array([65535]);
const result = tiffIfdToRgba(src, 1, 1, 1, 1);
expect(result[0]).toBe(255);
expect(result[1]).toBe(255);
expect(result[2]).toBe(255);
});
it('handles 16-bit zero values', () => {
const src = new Uint16Array([0, 0, 0]);
const result = tiffIfdToRgba(src, 1, 1, 3, 2);
expect(result[0]).toBe(0);
expect(result[1]).toBe(0);
expect(result[2]).toBe(0);
});
it('normalizes 16-bit RGBA including alpha', () => {
const src = new Uint16Array([65535, 32768, 0, 49152]);
const result = tiffIfdToRgba(src, 1, 1, 4, 2);
expect(result[0]).toBe(255);
expect(result[1]).toBe(128);
expect(result[2]).toBe(0);
expect(result[3]).toBe(192);
});
});
describe('Float32 images', () => {
it('normalizes float RGB (0.0-1.0) to 8-bit', () => {
const src = new Float32Array([1.0, 0.0, 0.5]);
const result = tiffIfdToRgba(src, 1, 1, 3, 2);
expect(result[0]).toBe(255);
expect(result[1]).toBe(0);
expect(result[2]).toBe(128);
expect(result[3]).toBe(255);
});
it('clamps float values above 1.0', () => {
const src = new Float32Array([1.5, 0.0, 0.0]);
const result = tiffIfdToRgba(src, 1, 1, 3, 2);
expect(result[0]).toBe(255);
});
it('clamps float values below 0.0', () => {
const src = new Float32Array([-0.5, 0.0, 0.0]);
const result = tiffIfdToRgba(src, 1, 1, 3, 2);
expect(result[0]).toBe(0);
});
it('normalizes float grayscale', () => {
const src = new Float32Array([0.5]);
const result = tiffIfdToRgba(src, 1, 1, 1, 1);
expect(result[0]).toBe(128);
expect(result[1]).toBe(128);
expect(result[2]).toBe(128);
});
});
describe('Float64 images', () => {
it('normalizes float64 RGB to 8-bit', () => {
const src = new Float64Array([1.0, 0.5, 0.0]);
const result = tiffIfdToRgba(src, 1, 1, 3, 2);
expect(result[0]).toBe(255);
expect(result[1]).toBe(128);
expect(result[2]).toBe(0);
});
});
describe('output buffer size', () => {
it('always outputs width * height * 4 bytes', () => {
const src1 = new Uint8Array([100, 200, 50]);
expect(tiffIfdToRgba(src1, 1, 1, 3, 2).length).toBe(4);
const src2 = new Uint8Array([100]);
expect(tiffIfdToRgba(src2, 1, 1, 1, 1).length).toBe(4);
const src3 = new Uint8Array(new Array(12).fill(128));
expect(tiffIfdToRgba(src3, 2, 2, 3, 2).length).toBe(16);
});
it('returns Uint8ClampedArray', () => {
const src = new Uint8Array([0, 0, 0]);
const result = tiffIfdToRgba(src, 1, 1, 3, 2);
expect(result).toBeInstanceOf(Uint8ClampedArray);
});
});
describe('edge cases', () => {
it('handles 1x1 pixel image', () => {
const src = new Uint8Array([42, 84, 126]);
const result = tiffIfdToRgba(src, 1, 1, 3, 2);
expect(Array.from(result)).toEqual([42, 84, 126, 255]);
});
it('handles 5+ channel images (uses first 4)', () => {
const src = new Uint8Array([10, 20, 30, 40, 99]);
const result = tiffIfdToRgba(src, 1, 1, 5, 2);
expect(result[0]).toBe(10);
expect(result[1]).toBe(20);
expect(result[2]).toBe(30);
expect(result[3]).toBe(40);
});
});
});