Skip to content

Commit 857f65e

Browse files
authored
Try generate url data (#3222)
wrap the draw image function in a try statement, if successful the image will be drawn in the canvas, if not return the data URL of the previous image
1 parent afdb07a commit 857f65e

File tree

2 files changed

+45
-18
lines changed

2 files changed

+45
-18
lines changed

packages/roosterjs-content-model-plugins/lib/imageEdit/utils/generateDataURL.ts

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -50,23 +50,27 @@ export function generateDataURL(image: HTMLImageElement, editInfo: ImageMetadata
5050
canvas.height = targetHeight * devicePixelRatio;
5151

5252
const context = canvas.getContext('2d');
53-
if (context) {
54-
context.scale(devicePixelRatio, devicePixelRatio);
55-
context.translate(targetWidth / 2, targetHeight / 2);
56-
context.rotate(angle);
57-
context.scale(editInfo.flippedHorizontal ? -1 : 1, editInfo.flippedVertical ? -1 : 1);
58-
context.drawImage(
59-
image,
60-
nWidth * left,
61-
nHeight * top,
62-
imageWidth,
63-
imageHeight,
64-
-width / 2,
65-
-height / 2,
66-
width,
67-
height
68-
);
69-
}
7053

71-
return canvas.toDataURL('image/png', 1.0);
54+
try {
55+
if (context) {
56+
context.scale(devicePixelRatio, devicePixelRatio);
57+
context.translate(targetWidth / 2, targetHeight / 2);
58+
context.rotate(angle);
59+
context.scale(editInfo.flippedHorizontal ? -1 : 1, editInfo.flippedVertical ? -1 : 1);
60+
context.drawImage(
61+
image,
62+
nWidth * left,
63+
nHeight * top,
64+
imageWidth,
65+
imageHeight,
66+
-width / 2,
67+
-height / 2,
68+
width,
69+
height
70+
);
71+
}
72+
return canvas.toDataURL('image/png', 1.0);
73+
} catch {
74+
return image.src;
75+
}
7276
}

packages/roosterjs-content-model-plugins/test/imageEdit/utils/generateDataURLTest.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,27 @@ describe('generateDataURL', () => {
2222
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAChJREFUOE9jZKAyYKSyeQyjBlIeoqNhOBqGZITAaLIhI9DQtIzAMAQASMYAFTvklLAAAAAASUVORK5CYII='
2323
);
2424
});
25+
26+
itChromeOnly('generate image url - draw image - error', () => {
27+
const editInfo = {
28+
src: 'test',
29+
widthPx: 0,
30+
heightPx: 0,
31+
naturalWidth: 0,
32+
naturalHeight: 0,
33+
leftPercent: 0,
34+
rightPercent: 0,
35+
topPercent: 0.1,
36+
bottomPercent: 0,
37+
angleRad: 0,
38+
};
39+
const image = document.createElement('img');
40+
image.width = 0; // Force error
41+
image.height = 0;
42+
image.src = 'https://th.bing.com/th/id/OIP.kJCCjl_yUweRlj94AdU-egHaFK?rs=1&pid=ImgDetMain';
43+
const url = generateDataURL(image, editInfo);
44+
expect(url).toBe(
45+
'https://th.bing.com/th/id/OIP.kJCCjl_yUweRlj94AdU-egHaFK?rs=1&pid=ImgDetMain'
46+
);
47+
});
2548
});

0 commit comments

Comments
 (0)