Skip to content

Commit

Permalink
adding code examples
Browse files Browse the repository at this point in the history
  • Loading branch information
catdad committed Nov 6, 2023
1 parent 0346cc4 commit ba1f205
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,67 @@ _Note: in the examples below, make sure to set the latest version when you use i
</script>
```

In all cases, you can use this sample code to decode an image:

```js
const file = fs.readFileSync('./temp/0002.heic');

const decoder = new libheif.HeifDecoder();
const data = decoder.decode(file);
// data in an array holding all images inside the heic file

const image = data[0];
const width = image.get_width();
const height = image.get_height();
```

In NodeJS, you might use this decoded data with other libraries, such as `pngjs`:

```js
const { PNG } = require('pngjs');

const arrayBuffer = await new Promise((resolve, reject) => {
image.display({ data: new Uint8ClampedArray(width*height*4), width, height }, (displayData) => {
if (!displayData) {
return reject(new Error('HEIF processing error'));
}

resolve(displayData.data.buffer);
});
});

const imageData = { width, height, data: arrayBuffer };

const png = new PNG({ width: imageData.width, height: imageData.height });
png.data = Buffer.from(imageData.data);

const pngBuffer = PNG.sync.write(png);
```

In the browser, you might use this decoded data with `canvas` to display or convert the image:

```js
const canvas = document.createElement('canvas');

canvas.width = width;
canvas.height = height;

const context = canvas.getContext('2d');
const imageData = context.createImageData(width, height);

await new Promise((resolve, reject) => {
image.display(imageData, (displayData) => {
if (!displayData) {
return reject(new Error('HEIF processing error'));
}

resolve();
});
});

context.putImageData(imageData, 0, 0);
```

## Related

This module contains the low-level `libheif` implementation. For more user-friendly functionality, check out these projects:
Expand Down

0 comments on commit ba1f205

Please sign in to comment.