Commit eea295b1 authored by dtati's avatar dtati

resize image

parent de2bc21d
import { Observable } from "rxjs";
export class ConfigHelper { export class ConfigHelper {
// information sent after creation of applicationId by mail // information sent after creation of applicationId by mail
...@@ -34,4 +36,65 @@ export class ConfigHelper { ...@@ -34,4 +36,65 @@ export class ConfigHelper {
} }
return bytes.buffer; return bytes.buffer;
} }
resizeImage(file: File): Observable<File> {
// in bytes, compress images larger than 1MB
const fileSizeMax = 1 * 1024 * 1024
const defaultQualityRatio = 0.7
const imageType = file.type || 'image/jpeg'
const reader = new FileReader()
reader.readAsDataURL(file)
return Observable.create((observer: { next: (arg0: File) => void; error: (arg0: ProgressEvent<FileReader>) => any }) => {
// This event is triggered each time the reading operation is successfully completed.
reader.onload = e => {
// Create an html image element
const img = this.createImage(e)
// Determines the ratios to compress the image
// let withHeightRatio = (imgWH > widthHeightMax) ? widthHeightMax/imgWH : defaultWidthHeightRatio
let qualityRatio = (file.size > fileSizeMax) ? fileSizeMax/file.size : defaultQualityRatio
// Fires immediately after the browser loads the object
img.onload = () => {
const canvas = document.createElement('canvas')
const ctx = <CanvasRenderingContext2D>canvas.getContext('2d')
// resize width, height
canvas.width = 1000;
canvas.height = 600;
if(img.width < img.height){
canvas.width = 600;
canvas.height = 1000;
}
if(img.width > canvas.width || img.height > canvas.height){
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
ctx.canvas.toBlob(
// callback, called when blob created
blob => {
observer.next(new File(
[blob!],
file.name,
{
type: imageType,
lastModified: Date.now(),
}
))
},
imageType,
qualityRatio, // reduce image quantity
)
}
}
}
// Catch errors when reading file
reader.onerror = error => observer.error(error)
})
}
private createImage(ev:any) {
let imageContent = ev.target.result
const img = new Image()
img.src = imageContent
return img
}
} }
\ No newline at end of file
...@@ -97,7 +97,9 @@ export class AppComponent implements OnInit { ...@@ -97,7 +97,9 @@ export class AppComponent implements OnInit {
var reader = new FileReader(); var reader = new FileReader();
reader.onload = this.handleReaderLoaded.bind(this); reader.onload = this.handleReaderLoaded.bind(this);
reader.readAsBinaryString(file); reader.readAsBinaryString(file);
this.binaryFile = file; this.helperSky.resizeImage(file).subscribe((imageCompressed : any) => {
this.binaryFile = imageCompressed;
});
this.next(); this.next();
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment