Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

functions.js 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // @flow
  2. let filterSupport;
  3. /**
  4. * Checks context filter support.
  5. *
  6. * @returns {boolean} True if the filter is supported and false if the filter is not supported by the browser.
  7. */
  8. export function checkBlurSupport() {
  9. if (typeof filterSupport === 'undefined') {
  10. const canvas = document.createElement('canvas');
  11. const ctx = canvas.getContext('2d');
  12. filterSupport = typeof ctx.filter !== 'undefined';
  13. canvas.remove();
  14. }
  15. return filterSupport;
  16. }
  17. /**
  18. * Convert blob to base64.
  19. *
  20. * @param {Blob} blob - The link to add info with.
  21. * @returns {Promise<string>}
  22. */
  23. export const blobToData = (blob: Blob): Promise<string> => new Promise(resolve => {
  24. const reader = new FileReader();
  25. reader.onloadend = () => resolve(reader.result.toString());
  26. reader.readAsDataURL(blob);
  27. });
  28. /**
  29. * Convert blob to base64.
  30. *
  31. * @param {string} url - The image url.
  32. * @returns {Object} - Returns the converted blob to base64.
  33. */
  34. export const toDataURL = async (url: string) => {
  35. const response = await fetch(url);
  36. const blob = await response.blob();
  37. const resData = await blobToData(blob);
  38. return resData;
  39. };
  40. /**
  41. * Resize image and adjust original aspect ratio.
  42. *
  43. * @param {Object} base64image - Base64 image extraction.
  44. * @param {number} width - Value for resizing the image width.
  45. * @param {number} height - Value for resizing the image height.
  46. * @returns {Object} Returns the canvas output.
  47. *
  48. */
  49. export async function resizeImage(base64image: any, width: number = 1920, height: number = 1080) {
  50. const img = document.createElement('img');
  51. img.src = base64image;
  52. /* eslint-disable no-empty-function */
  53. img.onload = await function() {};
  54. // Create an off-screen canvas.
  55. const canvas = document.createElement('canvas');
  56. const ctx = canvas.getContext('2d');
  57. // Set its dimension to target size.
  58. canvas.width = width;
  59. canvas.height = height;
  60. // Draw source image into the off-screen canvas.
  61. // TODO: keep aspect ratio and implement object-fit: cover.
  62. ctx.drawImage(img, 0, 0, width, height);
  63. // Encode image to data-uri with base64 version of compressed image.
  64. return canvas.toDataURL('image/jpeg', 0.5);
  65. }