Files
docx-js/src/file/media/media.ts

76 lines
2.0 KiB
TypeScript
Raw Normal View History

import * as fs from "fs";
2018-01-22 20:42:57 +00:00
import * as sizeOf from "image-size";
import * as path from "path";
2018-01-22 20:42:57 +00:00
2018-01-23 01:33:12 +00:00
import { IMediaData } from "./data";
export class Media {
2018-01-29 01:55:25 +00:00
private readonly map: Map<string, IMediaData>;
constructor() {
this.map = new Map<string, IMediaData>();
}
private createMedia(key: string, referenceId, dimensions, data: fs.ReadStream | Buffer, filePath?: string) {
2018-01-09 21:57:10 +00:00
const imageData = {
referenceId: referenceId,
stream: data,
path: filePath,
2018-01-09 21:57:10 +00:00
fileName: key,
2018-01-22 20:42:57 +00:00
dimensions: {
pixels: {
x: dimensions.width,
y: dimensions.height,
},
emus: {
x: dimensions.width * 9525,
y: dimensions.height * 9525,
},
},
2018-01-09 21:57:10 +00:00
};
this.map.set(key, imageData);
return imageData;
}
public getMedia(key: string): IMediaData {
const data = this.map.get(key);
if (data === undefined) {
throw new Error(`Cannot find image with the key ${key}`);
}
return data;
}
public addMedia(filePath: string, referenceId: number): IMediaData {
const key = path.basename(filePath);
const dimensions = sizeOf(filePath);
return this.createMedia(key, referenceId, dimensions, fs.createReadStream(filePath), filePath);
}
public addMediaWithData(fileName: string, data: Buffer, referenceId: number, width?, height?): IMediaData {
const key = fileName;
let dimensions;
if (width && height) {
dimensions = {
width: width,
2018-05-17 15:32:15 +02:00
height: height,
};
} else {
dimensions = sizeOf(data);
}
2018-05-17 15:32:15 +02:00
return this.createMedia(key, referenceId, dimensions, data);
}
public get array(): IMediaData[] {
const array = new Array<IMediaData>();
this.map.forEach((data) => {
array.push(data);
});
return array;
}
}