Skip to content
This repository has been archived by the owner on Jun 11, 2021. It is now read-only.

Commit

Permalink
Merge pull request #7 from bartholomej/aspect-ratio
Browse files Browse the repository at this point in the history
feat(service): add 'keep aspect ratio' option
  • Loading branch information
bergben committed Nov 8, 2017
2 parents b273ee3 + 491adf5 commit 8f29ffd
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/ng2-pica.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ export interface resizeBufferOptions {
export class Ng2PicaService {
constructor(@Inject(forwardRef(() => ImgExifService)) private imageExifService:ImgExifService){
}
public resize(files: File[], width: number, height: number): Observable<any> {
public resize(files: File[], width: number, height: number, keepAspectRatio: boolean = false): Observable<any> {
let resizedFile: Subject<File> = new Subject<File>();
files.forEach((file) => {
this.resizeFile(file, width, height).then((returnedFile) => {
this.resizeFile(file, width, height, keepAspectRatio).then((returnedFile) => {
resizedFile.next(returnedFile);
}).catch((error) => {
resizedFile.error(error);
Expand Down Expand Up @@ -76,7 +76,7 @@ export class Ng2PicaService {
return result;
}

private resizeFile(file: File, width: number, height: number): Promise<File> {
private resizeFile(file: File, width: number, height: number, keepAspectRatio: boolean = false): Promise<File> {
let result: Promise<File> = new Promise((resolve, reject) => {
let fromCanvas: HTMLCanvasElement = document.createElement('canvas');
let ctx = fromCanvas.getContext('2d');
Expand All @@ -88,6 +88,11 @@ export class Ng2PicaService {
fromCanvas.height = orientedImg.height;
ctx.drawImage(orientedImg, 0, 0);
let imageData = ctx.getImageData(0, 0, orientedImg.width, orientedImg.height);
if (keepAspectRatio) {
let ratio = Math.min(width / imageData.width, height / imageData.height);
width = Math.round(imageData.width * ratio);
height = Math.round(imageData.height * ratio);
}
let useAlpha = true;
if (file.type === "image/jpeg" || (file.type === "image/png" && !this.isImgUsingAlpha(imageData))) {
//image without alpha
Expand Down

0 comments on commit 8f29ffd

Please sign in to comment.