|
1 | | -import type { ImageCropData } from './types.ts'; |
| 1 | +import type { ImageCropData, CropResult } from './types.ts'; |
2 | 2 |
|
3 | 3 | function drawImage( |
4 | 4 | img: HTMLImageElement, |
@@ -51,16 +51,47 @@ function fetchImage(imgSrc: string): Promise<HTMLImageElement> { |
51 | 51 | const DEFAULT_COMPRESSION_QUALITY = 0.9; |
52 | 52 |
|
53 | 53 | class ImageEditor { |
54 | | - static cropImage(imgSrc: string, cropData: ImageCropData): Promise<string> { |
| 54 | + static cropImage(imgSrc: string, cropData: ImageCropData): CropResult { |
55 | 55 | /** |
56 | 56 | * Returns a promise that resolves with the base64 encoded string of the cropped image |
57 | 57 | */ |
58 | 58 | return fetchImage(imgSrc).then(function onfulfilledImgToCanvas(image) { |
| 59 | + const ext = cropData.format ?? 'jpeg'; |
| 60 | + const type = `image/${ext}`; |
| 61 | + const quality = cropData.quality ?? DEFAULT_COMPRESSION_QUALITY; |
59 | 62 | const canvas = drawImage(image, cropData); |
60 | | - return canvas.toDataURL( |
61 | | - `image/${cropData.format ?? 'jpeg'}`, |
62 | | - cropData.quality ?? DEFAULT_COMPRESSION_QUALITY |
63 | | - ); |
| 63 | + |
| 64 | + return new Promise<Blob | null>(function onfulfilledCanvasToBlob( |
| 65 | + resolve |
| 66 | + ) { |
| 67 | + canvas.toBlob(resolve, type, quality); |
| 68 | + }).then((blob) => { |
| 69 | + if (!blob) { |
| 70 | + throw new Error('Image cannot be created from canvas'); |
| 71 | + } |
| 72 | + |
| 73 | + let _path: string, _uri: string; |
| 74 | + |
| 75 | + return { |
| 76 | + width: canvas.width, |
| 77 | + height: canvas.height, |
| 78 | + name: 'ReactNative_cropped_image.' + ext, |
| 79 | + size: blob.size, |
| 80 | + // Lazy getters to avoid unnecessary memory usage |
| 81 | + get path() { |
| 82 | + if (!_path) { |
| 83 | + _path = URL.createObjectURL(blob); |
| 84 | + } |
| 85 | + return _path; |
| 86 | + }, |
| 87 | + get uri() { |
| 88 | + if (!_uri) { |
| 89 | + _uri = canvas.toDataURL(type, quality); |
| 90 | + } |
| 91 | + return _uri; |
| 92 | + }, |
| 93 | + }; |
| 94 | + }); |
64 | 95 | }); |
65 | 96 | } |
66 | 97 | } |
|
0 commit comments