Skip to content

Commit 2fac84b

Browse files
author
Kunjesh Kumar
committed
mobile out of memory optimisation for decoding large images
1 parent bc821c9 commit 2fac84b

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

src/imageLoader/decodeJPEGBaseline8BitColor.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,27 @@ function decodeJPEGBaseline8BitColor(imageFrame, pixelData, canvas) {
4343
fileReader.onload = function() {
4444
const img = new Image();
4545

46-
img.onload = function() {
46+
img.onload = function () {
47+
48+
const maxSize = Math.max(
49+
img.height,
50+
img.width
51+
)
52+
const maxSizeThresh = 1000
53+
54+
if (maxSize > maxSizeThresh) {
55+
const ratio = maxSizeThresh / maxSize
56+
img.width *= ratio
57+
img.height *= ratio
58+
}
59+
4760
canvas.height = img.height;
4861
canvas.width = img.width;
4962
imageFrame.rows = img.height;
5063
imageFrame.columns = img.width;
5164
const context = canvas.getContext('2d');
5265

53-
context.drawImage(this, 0, 0);
66+
context.drawImage(this, 0, 0,img.width,img.height);
5467
const imageData = context.getImageData(0, 0, img.width, img.height);
5568
const end = new Date().getTime();
5669

src/webWorker/decodeTask/decodeTask.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,40 @@ function handler(data, doneCallback) {
5858
);
5959
}
6060

61+
// snippet for resizing the image pixel data for Mobile
62+
if (imageFrame.samplesPerPixel === 1) {
63+
const maxSize = Math.max(imageFrame.columns, imageFrame.rows);
64+
const maxSizeThresh = 1000;
65+
if (maxSize > maxSizeThresh) {
66+
const factor = maxSize / maxSizeThresh;
67+
const width = imageFrame.columns; // width is columns
68+
const height = imageFrame.rows;
69+
const newWidth = Math.floor(width / factor);
70+
const newHeight = Math.floor(height / factor);
71+
72+
// create new array same type as original
73+
const resizedPixelData = new imageFrame.pixelData.constructor(
74+
newWidth * newHeight
75+
);
76+
// resize using nearest neighbour interpolation
77+
for (let i = 0; i < resizedPixelData.length; i++) {
78+
const x = i % newWidth;
79+
const y = Math.floor(i / newWidth);
80+
81+
const projX = Math.floor(x * factor);
82+
const projY = Math.floor(y * factor);
83+
const projI = projX + projY * width;
84+
85+
resizedPixelData[i] = imageFrame.pixelData[projI];
86+
}
87+
88+
imageFrame.columns = newWidth;
89+
imageFrame.rows = newHeight;
90+
imageFrame.pixelData = resizedPixelData;
91+
imageFrame.pixelDataLength = resizedPixelData.length;
92+
}
93+
}
94+
6195
calculateMinMax(imageFrame, strict);
6296

6397
// convert from TypedArray to ArrayBuffer since web workers support passing ArrayBuffers but not

0 commit comments

Comments
 (0)