jpeg_viewer.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* Copyright 2018 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. "use strict";
  16. if (!pdfjsImageDecoders.JpegImage) {
  17. // eslint-disable-next-line no-alert
  18. alert("Please build the pdfjs-dist library using `gulp dist-install`");
  19. }
  20. const JPEG_IMAGE = "fish.jpg";
  21. const jpegCanvas = document.getElementById("jpegCanvas");
  22. const jpegCtx = jpegCanvas.getContext("2d");
  23. (async function () {
  24. // Load the image data, and convert it to a Uint8Array.
  25. //
  26. const response = await fetch(JPEG_IMAGE);
  27. if (!response.ok) {
  28. throw new Error(response.statusText);
  29. }
  30. const typedArrayImage = new Uint8Array(await response.arrayBuffer());
  31. // Parse the image data using `JpegImage`.
  32. //
  33. const jpegImage = new pdfjsImageDecoders.JpegImage();
  34. jpegImage.parse(typedArrayImage);
  35. const width = jpegImage.width,
  36. height = jpegImage.height;
  37. const jpegData = jpegImage.getData({
  38. width,
  39. height,
  40. forceRGB: true,
  41. });
  42. // Render the JPEG image on a <canvas>.
  43. //
  44. const imageData = jpegCtx.createImageData(width, height);
  45. const imageBytes = imageData.data;
  46. for (let j = 0, k = 0, jj = width * height * 4; j < jj; ) {
  47. imageBytes[j++] = jpegData[k++];
  48. imageBytes[j++] = jpegData[k++];
  49. imageBytes[j++] = jpegData[k++];
  50. imageBytes[j++] = 255;
  51. }
  52. jpegCanvas.width = width;
  53. jpegCanvas.height = height;
  54. jpegCtx.putImageData(imageData, 0, 0);
  55. })();