Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use jimp to improve jpeg encoding #50

Merged
merged 1 commit into from
Apr 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions clis/glft-avatar-exporter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"dependencies": {
"three": "0.161.0",
"@napi-rs/canvas": "0.1.51",
"jimp": "0.22.12",
"gltf-avatar-export-lib": "file:../../packages/gltf-avatar-export-lib",
"yargs": "17.7.2"
},
Expand Down
25 changes: 23 additions & 2 deletions clis/glft-avatar-exporter/src/setupPolyfills.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { BinaryLike } from "node:crypto";
import process from "process";

import { Canvas, Image, ImageData, loadImage } from "@napi-rs/canvas";
import Jimp from "jimp";

/*
Blobs are accessed using global names - they must be accessible to code paths that create classes that read blobs
Expand Down Expand Up @@ -200,8 +201,28 @@ function createElement(elementName: string) {

(canvas as any).convertToBlob = async (options?: { type: string; quality?: number }) => {
const type = options?.type || "image/png";
const buffer = canvas.toBuffer(type as any, options?.quality);
const blob = new PolyfillBlobClass([new Uint8Array(buffer)], {
const asPngBuffer = canvas.toBuffer("image/png");

if (type === "image/jpeg" || type === "image/jpg") {
/*
If the requested type is jpeg, convert the image from png to jpeg using Jimp (avoids encoding quality issues
with canvas)
*/
return new Promise((resolve, reject) => {
Jimp.read(asPngBuffer, async (err, image) => {
if (err) {
return reject(err);
}
const jpegBuffer = await image.getBufferAsync(Jimp.MIME_JPEG);
const blob = new PolyfillBlobClass([new Uint8Array(jpegBuffer)], {
type: type,
});
resolve(blob);
});
});
}

const blob = new PolyfillBlobClass([new Uint8Array(asPngBuffer)], {
type: type,
});
return Promise.resolve(blob);
Expand Down
Loading
Loading