Convert examples/image_decoders/jpeg_viewer.js to await/async #14123

This commit is contained in:
Benson Imoh,ST 2021-10-19 23:22:44 +01:00
parent 52fce0d17b
commit f263c860bd
No known key found for this signature in database
GPG Key ID: 3BD60649DB0CD9C9

View File

@ -25,58 +25,39 @@ const JPEG_IMAGE = "fish.jpg";
const jpegCanvas = document.getElementById("jpegCanvas"); const jpegCanvas = document.getElementById("jpegCanvas");
const jpegCtx = jpegCanvas.getContext("2d"); const jpegCtx = jpegCanvas.getContext("2d");
// Load the image data, and convert it to a Uint8Array. (async function () {
// // Load the image data, and convert it to a Uint8Array.
let nonBinaryRequest = false; //
const request = new XMLHttpRequest(); const response = await fetch(JPEG_IMAGE);
request.open("GET", JPEG_IMAGE, false); if (!response.ok) {
try { throw new Error(response.statusText);
request.responseType = "arraybuffer";
nonBinaryRequest = request.responseType !== "arraybuffer";
} catch (e) {
nonBinaryRequest = true;
}
if (nonBinaryRequest && request.overrideMimeType) {
request.overrideMimeType("text/plain; charset=x-user-defined");
}
request.send(null);
let typedArrayImage;
if (nonBinaryRequest) {
const str = request.responseText,
length = str.length;
const bytes = new Uint8Array(length);
for (let i = 0; i < length; ++i) {
bytes[i] = str.charCodeAt(i) & 0xff;
} }
typedArrayImage = bytes; const typedArrayImage = new Uint8Array(await response.arrayBuffer());
} else {
typedArrayImage = new Uint8Array(request.response);
}
// Parse the image data using `JpegImage`. // Parse the image data using `JpegImage`.
// //
const jpegImage = new pdfjsImageDecoders.JpegImage(); const jpegImage = new pdfjsImageDecoders.JpegImage();
jpegImage.parse(typedArrayImage); jpegImage.parse(typedArrayImage);
const width = jpegImage.width, const width = jpegImage.width,
height = jpegImage.height; height = jpegImage.height;
const jpegData = jpegImage.getData({ const jpegData = jpegImage.getData({
width, width,
height, height,
forceRGB: true, forceRGB: true,
}); });
// Render the JPEG image on a <canvas>. // Render the JPEG image on a <canvas>.
// //
const imageData = jpegCtx.createImageData(width, height); const imageData = jpegCtx.createImageData(width, height);
const imageBytes = imageData.data; const imageBytes = imageData.data;
for (let j = 0, k = 0, jj = width * height * 4; j < jj; ) { for (let j = 0, k = 0, jj = width * height * 4; j < jj; ) {
imageBytes[j++] = jpegData[k++]; imageBytes[j++] = jpegData[k++];
imageBytes[j++] = jpegData[k++]; imageBytes[j++] = jpegData[k++];
imageBytes[j++] = jpegData[k++]; imageBytes[j++] = jpegData[k++];
imageBytes[j++] = 255; imageBytes[j++] = 255;
} }
jpegCanvas.width = width; jpegCanvas.width = width;
jpegCanvas.height = height; jpegCanvas.height = height;
jpegCtx.putImageData(imageData, 0, 0); jpegCtx.putImageData(imageData, 0, 0);
})();