expo-image-manipulator
Version:
Provides functions that let you manipulation images on the local file system, eg: resize, crop.
67 lines (65 loc) • 2.28 kB
JavaScript
import { CodedError, SharedRef } from 'expo';
import { SaveFormat } from '../ImageManipulator.types';
import { blobToBase64String, releaseCanvas } from './utils.web';
export default class ImageManipulatorImageRef extends SharedRef {
nativeRefType = 'image';
isReleased = false;
uri;
canvas;
constructor(uri, canvas){
super();
this.uri = uri;
this.canvas = canvas;
}
get width() {
this.ensureNotReleased();
return this.canvas.width;
}
get height() {
this.ensureNotReleased();
return this.canvas.height;
}
async saveAsync(options = {
base64: false
}) {
this.ensureNotReleased();
const width = this.width;
const height = this.height;
return new Promise((resolve, reject)=>{
const requestedType = `image/${options.format ?? SaveFormat.JPEG}`;
this.canvas.toBlob(async (blob)=>{
if (!blob) {
return reject(new Error(`Unable to save image: ${this.uri}`));
}
if (blob.type !== requestedType) {
return reject(new Error(`The browser does not support encoding "${requestedType}" images. Got "${blob.type}" instead. Try a different format like JPEG or PNG.`));
}
const base64 = options.base64 ? await blobToBase64String(blob) : undefined;
const uri = URL.createObjectURL(blob);
resolve({
uri,
width,
height,
base64
});
}, requestedType, options.compress);
});
}
release() {
if (this.isReleased) {
return;
}
this.isReleased = true;
if (this.uri.toLowerCase().startsWith('blob:')) {
URL.revokeObjectURL(this.uri);
}
releaseCanvas(this.canvas);
super.release();
}
ensureNotReleased() {
if (this.isReleased) {
throw new CodedError('ERR_IMAGE_MANIPULATOR_RELEASED', 'This image was released by release(). Render a new image with ImageManipulatorContext.renderAsync().');
}
}
}
//# sourceMappingURL=ImageManipulatorImageRef.web.js.map