Skip to content

Commit

Permalink
Merge pull request #2 from CatsJuice/feature/format-jpeg
Browse files Browse the repository at this point in the history
feature: add jpeg format support(only support white bg yet)
  • Loading branch information
CatsJuice committed Mar 4, 2022
2 parents 453161c + a2e9109 commit 60cd2f2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
15 changes: 13 additions & 2 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,22 @@ export class AppController {
res.header('Content-Type', 'text/html;charset=utf-8');
res.send(generateHtml(raw, username));
} else if (format === OutputFormat.PNG) {
res.header('Content-Type', 'image/svg;charset=utf-8');
res.header('Content-Type', 'image/png;charset=utf-8');
res.header('Content-Disposition', `inline; filename=${filename}.png`);
res.send(
await this.appService.transformSvg2Png(
await this.appService.transformSvg2Image(
raw,
'png',
Math.min(10, Math.max(0.1, parseFloat(`${query.quality}`) || 1)),
),
);
} else if (format === OutputFormat.JPEG) {
res.header('Content-Type', 'image/jpeg;charset=utf-8');
res.header('Content-Disposition', `inline; filename=${filename}.jpg`);
res.send(
await this.appService.transformSvg2Image(
raw,
'jpeg',
Math.min(10, Math.max(0.1, parseFloat(`${query.quality}`) || 1)),
),
);
Expand Down
14 changes: 9 additions & 5 deletions src/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,19 @@ export class AppService {
* @param resize
* @returns
*/
public async transformSvg2Png(svgRaw: string, resize = 1) {
public async transformSvg2Image(svgRaw: string, format: string, resize = 1) {
const buf = Buffer.from(svgRaw);
return await sharp(buf)
.metadata()
.then(({ width }) =>
sharp(buf)
.then(({ width }) => {
let ref = sharp(buf);
// TODO: add to configuration
if (format === 'jpeg') ref = ref.flatten({ background: '#fff' });
return ref
.toFormat(format)
.resize(Math.round(width * resize) * 2)
.toBuffer(),
);
.toBuffer();
});
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/dto/config-chart.query.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export enum OutputFormat {
XML = 'xml',
PNG = 'png',
HTML = 'html',
JPEG = 'jpeg',
}

export enum WidgetSize {
Expand Down Expand Up @@ -41,7 +42,7 @@ export class ConfigChartQueryDto {
format?: OutputFormat;

/**
* png quality, only works when format=png, [0.1, 10]
* png quality, only works when format=png|jpeg, [0.1, 10]
* @default {1}
*/
quality?: number;
Expand Down

0 comments on commit 60cd2f2

Please sign in to comment.