Advertisement
Guest User

imgresize

a guest
May 11th, 2023
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. export default function convert({ file, width, height, type }: { file: File, width: number, height: number, type: string }): Promise<File> {
  2. return new Promise(function (resolve, reject) {
  3. let allow = ['jpg', 'gif', 'bmp', 'png', 'jpeg', 'svg'];
  4. try {
  5. if (file.name && file.name.split(".").reverse()[0] && allow.includes(file.name.split(".").reverse()[0].toLowerCase()) && file.size && file.type) {
  6. let imageType = type ? type : 'jpeg';
  7. const imgWidth = width ? width : 500;
  8. const imgHeight = height ? height : 300;
  9. const fileName = file.name;
  10. const reader = new FileReader();
  11. reader.readAsDataURL(file);
  12. reader.onload = event => {
  13. if (event && event.target) {
  14. const img = new Image();
  15. img.src = event.target.result as string;
  16. img.onload = () => {
  17. const elem = document.createElement('canvas');
  18. elem.width = imgWidth;
  19. elem.height = imgHeight;
  20. const ctx = elem.getContext('2d');
  21. if (ctx) {
  22. ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
  23. ctx.canvas.toBlob((blob) => {
  24. if (blob) {
  25. const file = new File([blob], fileName, {
  26. type: `image/${imageType.toLowerCase()}`,
  27. lastModified: Date.now()
  28. });
  29. resolve(file)
  30. }
  31. }, 'image/jpeg', 1);
  32. }
  33. }, reader.onerror = error => reject(error);
  34. };
  35.  
  36. }
  37. } else reject('File not supported!')
  38. } catch (error) {
  39. console.log("Error while image resize: ", error);
  40. reject(error)
  41. }
  42. })
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement