Skip to content

Commit bcf5dc0

Browse files
committed
(#307) Implement image reader
1 parent 3a75981 commit bcf5dc0

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

Diff for: lib/provider/io/jimp-image-reader.class.spec.ts

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import ImageReader from "./jimp-image-reader.class";
2+
import {join} from "path";
3+
import {Image} from "../../image.class";
4+
5+
describe('Jimp image reader', () => {
6+
it('should return an Image object', async () => {
7+
// GIVEN
8+
const inputPath = join(__dirname, "__mocks__", "calculator.png");
9+
const expectedData = {
10+
width: 34,
11+
height: 28,
12+
data: expect.any(Buffer),
13+
channels: 3,
14+
pixelDensity: {
15+
scaleX: 1,
16+
scaleY: 1
17+
}
18+
}
19+
const SUT = new ImageReader();
20+
21+
// WHEN
22+
const result = await SUT.load(inputPath);
23+
24+
// THEN
25+
expect(result).toBeInstanceOf(Image);
26+
expect(result.width).toBe(expectedData.width);
27+
expect(result.height).toBe(expectedData.height);
28+
expect(result.data).toStrictEqual(expectedData.data);
29+
expect(result.channels).toBe(expectedData.channels);
30+
expect(result.pixelDensity).toStrictEqual(expectedData.pixelDensity);
31+
});
32+
33+
it('should reject on loading failures', async () => {
34+
// GIVEN
35+
const inputPath = "/fails/to/load";
36+
const expectedError = `Failed to load image from '${inputPath}'. Reason: Error: ENOENT: no such file or directory, open '${inputPath}'`;
37+
const SUT = new ImageReader();
38+
39+
// WHEN
40+
try {
41+
await SUT.load(inputPath);
42+
} catch (err) {
43+
// THEN
44+
expect(err).toBe(expectedError);
45+
}
46+
});
47+
});

Diff for: lib/provider/io/jimp-image-reader.class.ts

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import Jimp from 'jimp';
2+
import {ImageReader} from "../image-reader.type";
3+
import {Image} from "../../image.class";
4+
5+
export default class implements ImageReader {
6+
load(parameters: string): Promise<Image> {
7+
return new Promise<Image>((resolve, reject) => {
8+
Jimp.read(parameters)
9+
.then(jimpImage => {
10+
resolve(new Image(
11+
jimpImage.bitmap.width,
12+
jimpImage.bitmap.height,
13+
jimpImage.bitmap.data,
14+
jimpImage.hasAlpha() ? 4 : 3
15+
));
16+
}).catch(err => reject(`Failed to load image from '${parameters}'. Reason: ${err}`));
17+
})
18+
}
19+
}

0 commit comments

Comments
 (0)