Code Monkey home page Code Monkey logo

heic-convert's Introduction

heic-convert

Convert HEIC/HEIF images to JPEG and PNG

ci npm-downloads npm-version

Install

npm install heic-convert

Usage in NodeJS

Convert the main image in a HEIC to JPEG

const { promisify } = require('util');
const fs = require('fs');
const convert = require('heic-convert');

(async () => {
  const inputBuffer = await promisify(fs.readFile)('/path/to/my/image.heic');
  const outputBuffer = await convert({
    buffer: inputBuffer, // the HEIC file buffer
    format: 'JPEG',      // output format
    quality: 1           // the jpeg compression quality, between 0 and 1
  });

  await promisify(fs.writeFile)('./result.jpg', outputBuffer);
})();

Convert the main image in a HEIC to PNG

const { promisify } = require('util');
const fs = require('fs');
const convert = require('heic-convert');

(async () => {
  const inputBuffer = await promisify(fs.readFile)('/path/to/my/image.heic');
  const outputBuffer = await convert({
    buffer: inputBuffer, // the HEIC file buffer
    format: 'PNG'        // output format
  });

  await promisify(fs.writeFile)('./result.png', outputBuffer);
})();

Convert all images in a HEIC

const { promisify } = require('util');
const fs = require('fs');
const convert = require('heic-convert');

(async () => {
  const inputBuffer = await promisify(fs.readFile)('/path/to/my/image.heic');
  const images = await convert.all({
    buffer: inputBuffer, // the HEIC file buffer
    format: 'JPEG'       // output format
  });

  for (let idx in images) {
    const image = images[idx];
    const outputBuffer = await image.convert();
    await promisify(fs.writeFile)(`./result-${idx}.jpg`, outputBuffer);
  }
})();

The work to convert an image is done when calling image.convert(), so if you only need one of the images in a multi-image file, you can convert just that one from the images array and skip doing any work for the remaining images.

Note that while the converter returns a Promise and is overall asynchronous, a lot of work is still done synchronously, so you should consider using a worker thread in order to not block the main thread in highly concurrent production environments.

Usage in the browser

While the NodeJS version of heic-convert may be compiled for use in the browser with something like webpack, not all build tools necessarily like to compile all modules well. However, what further complicates things is that this module uses pure-javascript implementations of a jpeg and png encoder. But the browser has its own native encoders! Let's just use those instead of including a ton of extra code in your bundle.

When compiling a client-side project, use:

const convert = require('heic-convert/browser');

This is currently only supported in the main thread. Support for workers may be added in the future, but if you need it sooner, please create an issue or even a PR!

Related

  • heic-cli - convert heic/heif images to jpeg or png from the command line
  • heic-decode - decode heic images to raw image data
  • libheif-js - libheif as a pure-javascript npm module

heic-convert's People

Contributors

catdad avatar dependabot[bot] avatar jzarca01 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

heic-convert's Issues

Example of usage with a base64 string.

@catdad Thank you so much for this contribution! I was unfortunately struggling to get this working with our framework ParsePlatform https://parseplatform.org/

We get our files as based64 encoded strings. After converting them to a binary buffer I get this error

Could not parse HEIF file { code: ctor {}, subcode: ctor {} }
[]
ERROR:  Error: HEIF image not found
    at decodeBuffer (/Users/josephhanson/projects/app/node_modules/heic-decode/index.js:57:11)

The code snippet I am using to reproduce this is

 const mediaData = await media.source.getData(); // returns a base64 encoded string of the HEIC image
 const inputBuffer = Buffer.from(mediaData, 'base64');
 const outputBuffer = await convert({
     buffer: Buffer.from(inputBuffer.toString('binary')),
     format: 'JPEG',
     quality: 1,
 });

Do you happen to have an example of using this library with a base64 encoded image?

HEIF cannot convert to Jpg

Could not parse HEIF fileο½›
code:heif_error_code_heif_error_invalid_input
sub code:heif sub error code heif sub error end of data
}

Huge memory spike on one HEIC file

Hi,

Memory usage for a 10MB (16k x 3k) is about 300MB. However, the attached file uses over 2GB.

Note, to allow this to upload, I changed the file extension to GIF but this is a HEIC

Any thoughts?
79C140DD-E2DC-592F-A115-128FE2E950AB

Vulnerability in "jpeg-js" dependency found

Hi,

could you please Update jpeg-js to the latest version 0.4.4?

best regards
Matthias

Vulnerability found
 {
  "metadata": null,
  "vulnerable_versions": "<0.4.4",
  "module_name": "jpeg-js",
  "severity": "moderate",
  "github_advisory_id": "GHSA-xvf7-4v9q-58w6",
  "cves": [
    "CVE-2022-25851"
  ],
  "access": "public",
  "patched_versions": ">=0.4.4",
  "cvss": {
    "score": 0,
    "vectorString": null
  },
  "updated": "2022-06-17T01:00:49.000Z",
  "recommendation": "Upgrade to version 0.4.4 or later",
  "cwe": [
    "CWE-835"
  ],
  "found_by": null,
  "deleted": null,
  "id": 1070904,
  "references": "- https://nvd.nist.gov/vuln/detail/CVE-2022-25851\n- https://github.com/jpeg-js/jpeg-js/issues/105\n- https://github.com/jpeg-js/jpeg-js/pull/106/\n- https://github.com/jpeg-js/jpeg-js/commit/9ccd35fb5f55a6c4f1902ac5b0f270f675750c27\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSNPM-2860295\n- https://snyk.io/vuln/SNYK-JS-JPEGJS-2859218\n- https://github.com/advisories/GHSA-xvf7-4v9q-58w6",
  "created": "2022-06-11T00:00:17.000Z",
  "reported_by": null,
  "title": "Infinite loop in jpeg-js",
  "npm_advisory_id": null,
  "overview": "The package jpeg-js before 0.4.4 are vulnerable to Denial of Service (DoS) where a particular piece of input will cause to enter an infinite loop and never return.",
  "url": "https://github.com/advisories/GHSA-xvf7-4v9q-58w6"
}

Spread syntax requires ...iterable[Symbol.iterator] to be a function

hello
im trying to add heic file in my next js 14 app with formData on my windows machine using this code

const data = await req.formData();
const kk = data.get("kk") as File;
const kk_buffer = kk && kk instanceof Blob ? await kk.arrayBuffer() : undefined;
if (kk.name.split(".")[1] === "heic" || kk.name.split(".")[1] === "heif") {
	const kk_converted = await convert({
	  buffer: kk_buffer,
	  format: "JPEG",
	});
  console.log("πŸš€ ~ kk_converted:", kk_converted)
}

and i got error like this: Spread syntax requires ...iterable[Symbol.iterator] to be a function

is this because im upload from my windows machine?

Cannot pass non-string to std::string error

I'm trying to use this lib but keep getting this error:

  BindingError {
     name: 'BindingError',
     message: 'Cannot pass non-string to std::string',
     stack: 'BindingError: Cannot pass non-string to std::string\n' +
       '    at BindingError.<anonymous> (/Users/hisham/src/ess-app/packages/cli/node_modules/libheif-js/libheif/libheif.js:1:178858)\n' +
       '    at new BindingError (eval at createNamedFunction (/Users/hisham/src/ess-app/packages/cli/node_modules/libheif-js/libheif/libheif.js:18:11916), <anonymous>:4:34)\n' +
       '    at throwBindingError (/Users/hisham/src/ess-app/packages/cli/node_modules/libheif-js/libheif/libheif.js:1:182383)\n' +
       '    at Object.toWireType (/Users/hisham/src/ess-app/packages/cli/node_modules/libheif-js/libheif/libheif.js:1:209812)\n' +
       '    at Object.heif_context_read_from_memory (eval at new_ (/Users/hisham/src/ess-app/packages/cli/node_modules/libheif-js/libheif/libheif.js:1:203780), <anonymous>:8:26)\n' +
       '    at HeifDecoder.decode (/Users/hisham/src/ess-app/packages/cli/node_modules/libheif-js/libheif/libheif.js:18:10575)\n' +
       '    at decodeBuffer (/Users/hisham/src/ess-app/packages/cli/node_modules/heic-decode/index.js:52:24)\n' +
       '    at module.exports (/Users/hisham/src/ess-app/packages/cli/node_modules/heic-decode/index.js:69:46)\n' +
       '    at convert (/Users/hisham/src/ess-app/packages/cli/node_modules/heic-convert/index.js:39:25)\n' +
       '    at module.exports (/Users/hisham/src/ess-app/packages/cli/node_modules/heic-convert/index.js:56:70)\n' +
       '    at ImageService.convertHEICToJpeg (/Users/hisham/src/ess-app/packages/cli/src/utils/image.service.ts:26:22)\n' +
       '    at Object.<anonymous> (/Users/hisham/src/ess-app/packages/cli/src/utils/image.service.test.ts:14:39)\n' +
       '    at Object.asyncJestTest (/Users/hisham/src/ess-app/packages/cli/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:106:37)\n' +
       '    at /Users/hisham/src/ess-app/packages/cli/node_modules/jest-jasmine2/build/queueRunner.js:45:12\n' +
       '    at new Promise (<anonymous>)\n' +
       '    at mapper (/Users/hisham/src/ess-app/packages/cli/node_modules/jest-jasmine2/build/queueRunner.js:28:19)\n' +
       '    at /Users/hisham/src/ess-app/packages/cli/node_modules/jest-jasmine2/build/queueRunner.js:75:41\n' +
       '    at processTicksAndRejections (internal/process/task_queues.js:97:5)'
   }

Access to auxiliary images

Hi Kiril,

I see in the readme that it is possible to convert multiple images. However, does heic-convert also have a way to access embedded auxiliary images (e.g., Portrait photo depth map) as the non-JS version of heif-convert (the example app from libheif repo) does?

In other issues I saw you mention that heic-convert is based on the JS version of libheif. When checking heif_enscripten.h I see some references to auxiliary images, but I can't tell if the methods are actually implemented.

Many thanks in advance.

Thank you so much

Thank you so much for this awesome work finally i solved HEIC issue for my react native app :)

Wrong image rotation/orientation applied to output

Hi,

converting a HEIC image shot on an iPhone 13 to either a JPEG or PNG results into the image being flipped (wrongly rotated) for some images.
Looking at the EXIF data of the converted JPEG it looks like it just sets the orientation to 3 for every image.

image

I'll also attach the test HEIC file if you want to debug it (it's zipped because Github does not allow HEIC files)

heic.heic.zip

TypeError: Cannot read property 'slice' of undefined

With a multiple image heic

TypeError: Cannot read property 'slice' of undefined
    at uint8ArrayUtf8ByteString (/Users/jeremie/Desktop/dossier sans titre/node_modules/heic-decode/index.js:4:39)
    at isHeic (/Users/jeremie/Desktop/dossier sans titre/node_modules/heic-decode/index.js:10:22)
    at decodeBuffer (/Users/jeremie/Desktop/dossier sans titre/node_modules/heic-decode/index.js:47:8)
    at module.exports (/Users/jeremie/Desktop/dossier sans titre/node_modules/heic-decode/index.js:69:46)
    at convert (/Users/jeremie/Desktop/dossier sans titre/node_modules/heic-convert/index.js:39:25)
    at module.exports (/Users/jeremie/Desktop/dossier sans titre/node_modules/heic-convert/index.js:56:70)
    at init (/Users/jeremie/Desktop/dossier sans titre/heicextract.js:21:26)

Export isHEIC method

Before deciding to convert HEIC we need to first determine if the image is HEIC.

I could check mime, etc..but it seems your code already has an isHEIC method but it's not exported.

Currently you just throw an exception if image is not HEIC. And that exception is of type TypeError and has a string.

It would be great if you either expose isHEIC method or throw a more specific exception. Currently I'm catching the exception and parsing the message to determine if image is not HEIC, which is a brittle approach to determine if image is HEIC.

TypeError: input buffer is not a HEIC image when passing image from base64 buffer

Been trying to use heic-convert with an image that is passed as base64 string. Always getting TypeError: input buffer is not a HEIC image.

imagemagick:
~/Downloads/IMG_7316.HEIC HEIC 3024x4032 3024x4032+0+0 8-bit sRGB 2.32526MiB 0.020u 0:00.008

file command:
~/Downloads/IMG_7316.HEIC: ISO Media, HEIF Image HEVC Main or Main Still Picture Profile

This online base64 decoder also identifies the image as HEIC.

Code

const inputBuffer = Buffer.from(heicBase64String, 'base64');
const outputBuffer: Buffer = await convert({
  buffer: inputBuffer,
  format: 'JPEG', // output format
  quality: 0.85, // the jpeg compression quality, between 0 and 1
});

base64-string.txt
IMG_7316.HEIC.zip

5MB image take time almost 20 sec in AWS Lambda function

I am trying to convert heic image into jpeg.

1 => take image from s3 bucket.
2 => convert image ( quality => 0.35)
3 => save converted image on s3 bucket.

it takes almost 20+ sec for the whole process.

is there any way to reduce this time?

TypeError: input buffer is not a HEIC image

Hi @catdad πŸ‘‹πŸΌ πŸˆβ€β¬›

Human-dad here. Thanks for writing these modules. πŸ™πŸΌ

I"m trying to use heic-convert to convert a bunch of files exported from Google Photos with Google Takeout, but getting an error input buffer is not a HEIC image.

I created a repro repo here: https://github.com/zeke/heic-convert-test

Am I missing something obvious?


$ file flower.heic 

flower.heic: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, Exif Standard: [TIFF image data, big-endian, direntries=10, manufacturer=Apple, model=iPhone SE (2nd generation), orientation=upper-right, xresolution=167, yresolution=175, resolutionunit=2, software=15.1, datetime=2022:01:13 13:23:04, hostcomputer=iPhone SE (2nd generation)TIFF image data, big-endian, direntries=10, manufacturer=Apple, model=iPhone SE (2nd generation), orientation=upper-right, xresolution=167, yresolution=175, resolutionunit=2, software=15.1, datetime=2022:01:13 13:23:04, hostcomputer=iPhone SE (2nd generation)], baseline, precision 8, 4032x3024, components 3
{
  inputBuffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 17 0a 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 0a 01 0f 00 02 00 00 00 06 00 00 ... 2150157 more bytes>
}
TypeError: input buffer is not a HEIC image
    at decodeBuffer (/Users/z/Desktop/heic-convert-test/node_modules/heic-decode/index.js:48:11)
    at module.exports (/Users/z/Desktop/heic-convert-test/node_modules/heic-decode/index.js:69:46)
    at convert (/Users/z/Desktop/heic-convert-test/node_modules/heic-convert/index.js:39:25)
    at module.exports (/Users/z/Desktop/heic-convert-test/node_modules/heic-convert/index.js:56:70)
    at /Users/z/Desktop/heic-convert-test/index.js:9:30

Uncaught TypeError: util.inherits is not a function

Hi there,

I'd like to report an issue. After installing 'heic-convert' in my Vue project and attempting to import it into my components, I encountered the following error: "Uncaught TypeError: util.inherits is not a function." Could you please provide insights into the cause of this error?

Convert many heic pictures into many jpec ones

Hi

In one of the examples you give in the manual it is assumed that one single heic file contains many single pictures.

I have following use case:

  • I need to convert many single files, whose file format is heic, inside of one folder into jpeg files. Each of the mentioned heic files does only contain one single image.

IΒ΄m javascript beginner and donΒ΄t know how to solve this since using your script only one single heic file is converted into multiple jpec files.

Any idea how to solve this by adapting your example script Convert the main image in a HEIC to PNG ?

I look forward to your reply.

Thanks in advance.

Best

Sam

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.