image-js / tiff

TIFF image decoder written entirely in JavaScript
MIT License
190 stars 17 forks source link

Broken generated image from decoded data #45

Closed AliBayatMokhtari closed 1 year ago

AliBayatMokhtari commented 1 year ago

I have decoded this file: Link and the output is Preview or Download

the source code for getting image/png file is:

/** buffer is of type ArrayBuffer which is read from sample file */
const tiffIfds = decode(buffer);

const first = tiffIfds[0];

const canvas = document.createElement("canvas");
canvas.width = first.width;
canvas.height = first.height;

const ctx = canvas.getContext("2d", { alpha: first.alpha });

const imageData = ctx?.createImageData(canvas.width, canvas.height);
imageData?.data.set(first.data);

ctx?.putImageData(imageData!, 0, 0);

const pngImage = canvas.toDataURL("image/png");

const imgEl = document.getElementById("my-image") as HTMLImageElement;

if (imgEl) imgEl.src = pngImage;

and the HTML markup is simple as:

<div>
    <img id="my-image" />
</div>
targos commented 1 year ago

The problem is that you cannot just set the image data like that, because this tiff file has only three channels (RGB, no alpha). ImageData objects always contain RGBA data.

AliBayatMokhtari commented 1 year ago

The problem is that you cannot just set the image data like that, because this tiff file has only three channels (RGB, no alpha). ImageData objects always contain RGBA data.

So how can i convert such image to image/png base64? Any clue would be helpful. Thank uou

targos commented 1 year ago

You can use image-js:

import { Image } from 'image-js';
const img = await Image.load(data);
const url = img.toDataURL()

Feel free to ask more questions, but I'm closing this issue because the data returned by the decoder is correct.