Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
getImage = async (imageUrl: string) => {
try {
const localCopy = await RNFetchBlob.config({ fileCache: true }).fetch(
'GET',
imageUrl
)
const type = getImageType(imageUrl)
const resizedImage = await ImageResizer.createResizedImage(
localCopy.path(),
20,
20,
type,
80
)
// if we are on Android, then we have a faster native solution
// to get color from image, so we will use native for Android
if (Platform.OS === 'android') {
const rgb = await getColor(resizedImage.path)
this.updateTheme([rgb])
return
}
const base64EncodedImage = await RNFetchBlob.fs.readFile(
let failed = false;
await RNFS.mkdir(photoPath(), { NSURLIsExcludedFromBackupKey: true })
.catch((err) => {
consolelog(`DEBUG camera: mkdir error: ${err}`);
onPhotoTaken(undefined, new Error('Could not take a photo: could not create a folder for the photos.'));
failed = true;
});
if (failed) { return; }
// save to camera roll. Could grab the URI to the asset here, currently unused.
await CameraRoll.saveToCameraRoll(uri)
.catch((err) => { // not a failure: user might not want them saved to camera roll
consolelog(`DEBUG camera: save to camera roll failed, continuing: ${err}`);
});
const response = await ImageResizer.createResizedImage(uri, 2000, 2000, 'JPEG', 60)
.catch((err) => {
consolelog('DEBUG camera: resize ERROR:');
consolelog(err);
onPhotoTaken(undefined, new Error('Could not take a photo: there was an error resizing the photo.'));
failed = true;
});
if (failed) { return; }
await RNFS.unlink(uri)
.catch((err) => { // not a failure
consolelog(`DEBUG camera: could not delete full-sized photo: ${err}`);
});
const destPathResized = photoPath() + '/' + destFilenameResized;
await RNFS.moveFile(response.uri, destPathResized)
.catch((err) => {
// rotate will be defined if the original photo failed to rotate (this
// happens on low-memory devices) so we rotate the preview and
// thumbnail (rotating the smaller images seems to work ok).
const { uri: thumbnailUri } = await ImageResizer.createResizedImage(
originalUri,
THUMBNAIL_SIZE,
THUMBNAIL_SIZE,
"JPEG",
THUMBNAIL_QUALITY,
rotate
);
if (didCancel) throw new Error("Cancelled");
log("created thumbnail");
bugsnag.leaveBreadcrumb("Generated thumbnail", { type: "process" });
photo.thumbnailUri = thumbnailUri;
const { uri: previewUri } = await ImageResizer.createResizedImage(
originalUri,
PREVIEW_SIZE,
PREVIEW_SIZE,
"JPEG",
PREVIEW_QUALITY,
rotate
);
if (didCancel) throw new Error("Cancelled");
log("created preview");
bugsnag.leaveBreadcrumb("Generated preview", { type: "process" });
photo.previewUri = previewUri;
return photo;
}
function addMimeType(attachment: { id: string }): ObservationAttachment {
return function({ uri, exif, width, height }) {
const originalUri = uri;
let resizedUri;
const resizePromise = ImageResizer.createResizedImage(
uri,
width,
height,
"JPEG",
captureQuality,
rotation
)
.then(({ uri }) => {
bugsnag.leaveBreadcrumb("Rotate photo", { type: "process" });
// Image resizer uses `JPEG` as the extension, which gets passed through
// to mapeo-core media store. Change to `jpg` to match legacy photos and
// avoid issues on Windows (don't know if it recognizes `JPEG`)
resizedUri = uri.replace(/\.JPEG$/, ".jpg");
return RNFS.moveFile(uri, resizedUri);
})
.then(() => {
async resizeImage(localFilePath, targetPath, mimeType) {
const maxSize = Resource.IMAGE_MAX_DIMENSION;
let dimensions = await this.imageDimensions(localFilePath);
reg.logger().info('Original dimensions ', dimensions);
if (dimensions.width > maxSize || dimensions.height > maxSize) {
dimensions.width = maxSize;
dimensions.height = maxSize;
}
reg.logger().info('New dimensions ', dimensions);
const format = mimeType == 'image/png' ? 'PNG' : 'JPEG';
reg.logger().info(`Resizing image ${localFilePath}`);
const resizedImage = await ImageResizer.createResizedImage(localFilePath, dimensions.width, dimensions.height, format, 85); // , 0, targetPath);
const resizedImagePath = resizedImage.uri;
reg.logger().info('Resized image ', resizedImagePath);
reg.logger().info(`Moving ${resizedImagePath} => ${targetPath}`);
await RNFS.copyFile(resizedImagePath, targetPath);
try {
await RNFS.unlink(resizedImagePath);
} catch (error) {
reg.logger().warn('Error when unlinking cached file: ', error);
}
}
ImagePicker.showImagePicker(options, (response) => {
var source = null;
var fileName = null;
if (response.error) {
showAlert(transError.attachmentErrorTitle, transError.attachmentErrorMessage, transError.attachmentError);
} else if (response.didCancel) {
source = null;
} else {
if (Platform.OS === 'ios') {
source = {uri: response.uri.replace('file://', ''), isStatic: true};
} else {
source = {uri: response.uri, isStatic: true};
}
ImageResizer.createResizedImage(response.uri, Config.IMAGE_MAX_HEIGHT,
Config.IMAGE_MAX_WIDTH, Config.IMAGE_FORMAT, Config.IMAGE_QUALITY).then((resizedImageUri) => {
var resizedSource = {uri: resizedImageUri, isStatic: true}
response.path = resizedImageUri
response.uri = resizedImageUri;
this.setState({
image: {source: resizedSource, name: response.fileName},
imageData: response
});
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
}).catch((err) => {
showAlert(transError.feedbackImageErrorTitle, transError.feedbackImageErrorMessage, transError.feedbackImageErrorButton)
});
return new Promise((resolve, reject) => {
if (!pictureURI) { return resolve(); }
let targetPath = FileUtil.getPath(targetFilename);
ImageResizer.createResizedImage(pictureURI, screenWidth * pxRatio * scaleFactor, screenHeight * pxRatio * scaleFactor, 'JPEG', 90)
.then(({uri}) => {
return FileUtil.safeMoveFile(uri, targetPath);
})
.then(() => {
return FileUtil.safeDeleteFile(pictureURI);
})
.then(() => {
resolve(targetPath);
})
.catch((err) => {
reject("picture resizing error:" + err.message);
});
})
};
export function resize(data, width, height) {
return ImageResizer.createResizedImage(`data:image/jpeg;base64,${data}`, width, height, 'JPEG', 80).
then((resized) => readFileAsBase64(resized.path)).
then((final) => `data:image/jpeg;base64,${final}`)
}
export const getOptimizedMediaObject = async (originalMedia: IPickerImage) => {
let optimizedImagePath;
if (originalMedia.mime.startsWith(MediaTypeImage.key)) {
const optimized = await ImageResizer.createResizedImage(
originalMedia.path,
originalMedia.width,
originalMedia.height,
'JPEG',
50,
);
optimizedImagePath = optimized.path;
}
return {
...originalMedia,
optimizedImagePath,
type: originalMedia.mime,
};
};
export const resizeKYCImage = async (imageURI: string, imageData: string) => {
const IMAGE_TARGET_SIZE = 1024
let resizedImageResponse, base64ImageData
if (Platform.OS === 'android') {
resizedImageResponse = await ImageResizer.createResizedImage(imageURI, IMAGE_TARGET_SIZE, IMAGE_TARGET_SIZE, "JPEG", 100, 0)
base64ImageData = await RNFetchBlob.fs.readFile(resizedImageResponse.path, 'base64')
} else {
resizedImageResponse = await ImageResizer.createResizedImage(`data:image/jpg;jpeg;base64,${imageData}`, IMAGE_TARGET_SIZE, IMAGE_TARGET_SIZE, "JPEG", 100, 0)
base64ImageData = await RNFetchBlob.fs.readFile(resizedImageResponse.path, 'base64')
}
return `data:image/jpg;jpeg;base64,${base64ImageData}`
}