Rotate image and save in React-Native - ios

I am going to rotate the image in react–native and I would like to get base64 of rotated image.
I used several libraries
react-native-image-rotate: It's working well on Android but on iOS I get rct-image-store://1 as url so I tried getting base64 using rn-fetch-blob but it throws error that can't recognize that url.
react-native-image-resizer: I used this but the response is not good in iOS. If I set -90 then rotate -180, if I set -180 then it's rotating as -270.
Please help me on this problem, how can I rotate the image in iOS.
I need to rotate the image as -90, -180, -270, -360(original).

Finally, I found answer.
import ImageRotate from 'react-native-image-rotate';
import ImageResizer from 'react-native-image-resizer';
import RNFetchBlob from 'rn-fetch-blob';
ImageRotate.rotateImage(
this.state.image.uri,
rotateDegree,
uri => {
if (Platform.OS === 'android') {
console.log('rotate', uri);
RNFetchBlob.fs.readFile(uri, 'base64').then(data => {
const object = {};
object.base64 = data;
object.width = this.state.image.height;
object.height = this.state.image.width;
object.uri = uri;
this.setState({image: object, spinner: false});
});
} else {
console.log(uri);
const outputPath = `${RNFetchBlob.fs.dirs.DocumentDir}`;
ImageResizer.createResizedImage(
uri,
this.state.image.height,
this.state.image.width,
'JPEG',
100,
0,
outputPath,
).then(response => {
console.log(response.uri, response.size);
let imageUri = response.uri;
if (Platform.OS === 'ios') {
imageUri = imageUri.split('file://')[1];
}
RNFetchBlob.fs.readFile(imageUri, 'base64').then(resData => {
const object = {};
object.base64 = resData;
object.width = this.state.image.height;
object.height = this.state.image.width;
object.uri = response.uri;
this.setState({image: object, spinner: false});
});
});
}
},
error => {
console.error(error);
},
);
}

This is my work well code up to now
rotateImage = (angle) => {
const { currentImage } = this.state; // origin Image, you can pass it from params,... as you wish
ImageRotate.rotateImage( // using 'react-native-image-rotate'
currentImage.uri,
angle,
(rotatedUri) => {
if (Platform.OS === 'ios') {
ImageStore.getBase64ForTag( // import from react-native
rotatedUri,
(base64Image) => {
const imagePath = `${RNFS.DocumentDirectoryPath}/${new Date().getTime()}.jpg`;
RNFS.writeFile(imagePath, `${base64Image}`, 'base64') // using 'react-native-fs'
.then(() => {
// now your file path is imagePath (which is a real path)
if (success) {
this.updateCurrentImage(imagePath, currentImage.height, currentImage.width);
ImageStore.removeImageForTag(rotatedUri);
}
})
.catch(() => {});
},
() => {},
);
} else {
this.updateCurrentImage(rotatedUri, currentImage.height, currentImage.width);
}
},
(error) => {
console.error(error);
},
);
};
I think you have done rotatedUri.
Then you can get base64 by ImageStore from react-native.
Then write it to the local image with react-native-fs
After that you have imagePath is the local image.

Try to use Expo Image Manipulator
https://docs.expo.io/versions/latest/sdk/imagemanipulator/
const rotated = await ImageManipulator.manipulateAsync(
image.uri,
[{ rotate: -90 }],
{ base64: true }
);

Related

Capacitor iOS Geolocation watchPostion kCLErrorDomain error 1 while permission granted

I am using an older version of the capacitor geolocation, v1.3.1, and recently switched to the watchPosition implementation but occasionally that created a situation where the position is null or undefined even when the device is showing the location icon being active for the app. I tried to solve that by falling back to the slower getCurrentPosition function but still persists. Has anyone run into this issue before? Here is a gist of the hook.
https://gist.github.com/billpull/8bc6e49872cfee29aa5cef193b59c835
useCurrentPosition.ts
const useCurrentPosition = (): GeoWatchPositionResult => {
const [position, setPosition] = useState<Position>();
const [watchId, setWatchId] = useState("");
const [error, setError] = useState();
const clearWatch = () => {
if (watchId) {
clearPosition({ id: watchId });
setWatchId("");
}
};
const startWatch = async () => {
if (!watchId) {
const id = await watchPosition(async (pos: Position | null, err) => {
if (err) {
setError(err);
}
if (pos) {
setPosition(pos);
} else {
const newPosition = await getCurrentPosition();
setPosition(newPosition);
}
});
setWatchId(id);
}
};
useEffect(() => {
startWatch();
return () => clearWatch();
}, []);
return { currentPosition: position, error };
};
Even though the watchPosition is still returning location data on the interval I am getting a kCLErrorDomain error 1. which online says it means the permission was denied but thats not the case the phone was just in sleep mode. Is there a way to catch this error specifically? Should I clear the watch and restart it on this error?
Edit:
One attempt I made was to use a try catch in the watch, but I still have encountered this issue.
const useCurrentPosition = (): GeoWatchPositionResult => {
const [position, setPosition] = useState<Position>();
const [watchId, setWatchId] = useState("");
const [error, setError] = useState();
const clearWatch = () => {
if (watchId) {
clearPosition({ id: watchId });
setWatchId("");
}
};
const startWatch = async () => {
if (!watchId) {
const id = await watchPosition(async (pos: Position | null, err) => {
try {
if (err) {
setError(err);
}
if (pos) {
setPosition(pos);
} else {
const newPosition = await getCurrentPosition();
setPosition(newPosition);
}
} catch (ex) {
await requestPermission();
clearWatch();
await startWatch();
}
});
setWatchId(id);
}
};
useEffect(() => {
startWatch();
return () => clearWatch();
}, []);
return { currentPosition: position, error };
};
I think you should use this code snippet to check the current position.
import { Geolocation, Geoposition } from '#ionic-native/geolocation/ngx';
constructor(private geolocation: Geolocation) { }
...
let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
// data can be a set of coordinates, or an error (if an error occurred).
// data.coords.latitude
// data.coords.longitude
});
You can also use the following code snippet to get the current position.
this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
}).catch((error) => {
console.log('Error getting location', error);
});
If you want to handle the permission denied error, the best way to handle the permission denied error is to check the permission status of the app first before trying to access any location data. This can be done by using the Capacitor Permissions API. If the permission has been granted, you can then proceed to use the watchPosition or getCurrentPosition APIs. If the permission has been denied, you can present a prompt to the user to request permission again.
setState is an asynchronous function, so please pass to it an anonymous function:
if (pos) {
setPosition(pos);
} else {
const newPosition = await getCurrentPosition();
setPosition(() => newPosition);
}

ios converting file to blob in CDVWKWebViewEngine ionic cordova angularJS

Just trying my luck here.
I've been tasked to update a Ionic 1, AngularJS, Cordova app for the changes in iOS camera and file permissions.
In most areas on the app I can simply convertFileSrc and trustAsResourceUrl to retrieve and display in the app. In the scenario below I need to convert the new safe ionic path to a blob for posting.
original file path format:
file:///var/mobile/Containers/Data/Application/10298A9F-7E24-48C4-912D-996EA731F2B0/Library/NoCloud/cdv_photo_001.jpg
after sanitising:
ionic://localhost/app_file/var/mobile/Containers/Data/Application/10298A9F-7E24-48C4-912D-996EA731F2B0/Library/NoCloud/cdv_photo_001.jpg
below is what I've tried so far:
function getDirectory(path) {
return path.substr(0, path.lastIndexOf('/'));
}
function getFilename(path) {
return path.substr(path.lastIndexOf('/') + 1);
}
function getImage(path) {
const pathStr = path;
if (window.ionic.Platform.isIOS() && typeof path === 'string') {
const fixedURL = window.Ionic.WebView.convertFileSrc(path);
path = $sce.trustAsResourceUrl(fixedURL);
}
if (typeof navigator.camera === 'undefined') {
return window.fetch(path, { method: 'GET' })
.then(function(response) {
return response.blob();
});
}
const filename = getFilename(`${path}`);
const directory = getDirectory(`${path}`);
return $cordovaFile.readAsArrayBuffer(directory, filename)
.catch(function(error) {
const err = {
message: 'read failed for image',
filename,
directory,
error
};
$log.error(`getImage, Error: ${JSON.stringify(err)}`);
return $q.reject(err);
})
.then(function(data) {
return new Blob([data], { type: 'image/jpeg' });
});
}
for anyone else who might need to do this in the future I figured out that it was the location of saved files casuing the problem.
In the cordova getPicture config I just needed to add
saveToPhotoAlbum: true
from there the file can just be pulled with the fetch api within the need for $cordovaFile:
return window.fetch(path, { method: 'GET' })
.then(function(response) {
return response.blob();
});

Download image not working on IOS device - React Native

I implemented functionality for download image in React Native using RNFetchBlob Its Working fine with android but on IOS device it's not working.
Following is my react native code for download functionality.
downloadImg = (url) => {
var that = this;
async function requestCameraPermission() {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'Test App',
message: 'Test App needs access to your gallery ',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
that.actualDownload(url);
} else {
Alert.alert('Permission Denied!', 'You need to give storage permission to download the file');
}
}
if (Platform.OS === 'android') {
requestCameraPermission();
} else {
this.actualDownload(url);
}
}
actualDownload = (url) => {
var date = new Date();
var image_URL = url;
var ext = this.getExtention(image_URL);
ext = "." + ext[0];
const { config, fs } = RNFetchBlob;
let PictureDir = Platform.OS === 'ios' ? fs.dirs.DocumentDir : fs.dirs.PictureDir;
let options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
path: PictureDir + "/Images/image_" + Math.floor(date.getTime()
+ date.getSeconds() / 2) + ext,
description: 'Image'
}
}
config(options).fetch('GET', image_URL).then((res) => {
console.log("Thank you","Image Downloaded Successfully.");
});
}
the addAndroidDownloads only works for android. when you use the addAndroidDownloads the path in config is not useless. but for ios, the path has to be added.
try the following code, and you can add progress for ios.
actualDownload = (url) => {
var date = new Date();
var image_URL = url;
var ext = this.getExtention(image_URL);
ext = "." + ext[0];
const { config, fs } = RNFetchBlob;
let PictureDir = Platform.OS === 'ios' ? fs.dirs.DocumentDir : fs.dirs.PictureDir;
let options = {
fileCache: true,
path: PictureDir + "/Images/image_" + Math.floor(date.getTime() // add it
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
path: PictureDir + "/Images/image_" + Math.floor(date.getTime()
+ date.getSeconds() / 2) + ext,
description: 'Image'
}
}
config(options).fetch('GET', image_URL).then((res) => {
console.log("Thank you","Image Downloaded Successfully.");
});
}
here are the document says:
When using DownloadManager, fileCache and path properties in config will not take effect, because Android DownloadManager can only store files to external storage, also notice that Download Manager can only support GET method, which means the request body will be ignored.
That method works for ios as well. The notification doesn't come. If you want to check that it is downloaded or not, you can check it by logging the path in terminal(Mac) or cmd(Windows) and access it through the terminal itself.
It might not be visible in finder(Mac) or file explorer(Windows).
You can follow the path that you log from the function in this way:
cd ~/Library/Developer/CoreSimulator/Devices...

How to upload images faster on iOS, when using takePictureAsync?

We have an app, created with React Native, where the user can take a picture and save it to his account. So we are sending the photo to our server. The problem is, that this takes really much time (about 20 to 30 seconds) on iOS. With the Android-Build it is much faster (about 2 seconds).
We have tried to reduce the quality of the pictures, but that has also not a big effect.
takePicture = async function(camera) {
const options = {
quality: 0.5,
fixOrientation: true,
forceUpOrientation: true
};
const data = await camera.takePictureAsync(options);
this.props.onCapture(data);
};
We would like to achieve the same uploading-time like on Android. Can someone help?
I've written the following function. After taking image it returns the original and resized image which takes around 500KB on iOS.
It uses ImagePicker package.
const pickImage = async (index) => {
const { status: cameraPerm } = await Permissions.askAsync(Permissions.CAMERA);
const { status: cameraRollPerm } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
import * as ImagePicker from 'expo-image-picker'
if (cameraPerm === "granted" && cameraRollPerm === "granted") {
let pickerResult;
if (index == 0 || index == undefined) {
pickerResult = await ImagePicker.launchCameraAsync({ allowsEditing: false, aspect: [4, 3], quality: 1 });
}
else if (index == 1) {
pickerResult = await ImagePicker.launchImageLibraryAsync({ allowsEditing: false, aspect: [4, 3], quality: 1 });
}
if (!pickerResult.cancelled) {
let resizedImage = await ImageManipulator.manipulateAsync(
pickerResult.uri, [{ resize: { width: 1200 } }],
{ compress: 1, format: "jpg", base64: false });
return [resizedImage.uri, pickerResult.uri];
} else {
return
}
} else {
alert(Messages.userManagement.cameraPermissions);
return
}
Then you can call above method like this.
let [resizedImage, originalImage] = await pickImage();

MediaRecorder Blob to file in an electron app

I have an electron app that has very simple desktop capturing functionality:
const {desktopCapturer} = require('electron')
const fs = require('fs');
var recorder;
var chunks = [];
var WINDOW_TITLE = "App Title";
function startRecording() {
desktopCapturer.getSources({ types: ['window', 'screen'] }, function(error, sources) {
if (error) throw error;
for (let i = 0; i < sources.length; i++) {
let src = sources[i];
if (src.name === WINDOW_TITLE) {
navigator.webkitGetUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: src.id,
minWidth: 800,
maxWidth: 1280,
minHeight: 600,
maxHeight: 720
}
}
}, handleStream, handleUserMediaError);
return;
}
}
});
}
function handleStream(stream) {
recorder = new MediaRecorder(stream);
chunks = [];
recorder.ondataavailable = function(event) {
chunks.push(event.data);
};
recorder.start();
}
function stopRecording() {
recorder.stop();
toArrayBuffer(new Blob(chunks, {type: 'video/webm'}), function(ab) {
var buffer = toBuffer(ab);
var file = `./test.webm`;
fs.writeFile(file, buffer, function(err) {
if (err) {
console.error('Failed to save video ' + err);
} else {
console.log('Saved video: ' + file);
}
});
});
}
function handleUserMediaError(e) {
console.error('handleUserMediaError', e);
}
function toArrayBuffer(blob, cb) {
let fileReader = new FileReader();
fileReader.onload = function() {
let arrayBuffer = this.result;
cb(arrayBuffer);
};
fileReader.readAsArrayBuffer(blob);
}
function toBuffer(ab) {
let buffer = new Buffer(ab.byteLength);
let arr = new Uint8Array(ab);
for (let i = 0; i < arr.byteLength; i++) {
buffer[i] = arr[i];
}
return buffer;
}
// Record for 3.5 seconds and save to disk
startRecording();
setTimeout(function() { stopRecording() }, 3500);
I know that to save the MediaRecorder blob sources, I need to read it into an ArrayBuffer, then copy that into a normal Buffer for the file to be saved.
However, where this seems to be failing for me is combining the chunk of blobs into blobs. When the chunks are added into a single Blob - it's like they just disappear. The new Blob is empty, and every other data structure they are copied into afterwards also is completely empty.
Before creating the Blob, I know I have valid Blob's in the chunks array.
Here's what the debug info of chunks is, before executing the new Blob(chunks, {.. part.
console.log(chunks)
Then here's the debug info of the new Blob(chunks, {type: 'video/webm'}) object.
console.log(ab)
I'm completely stumped. All the reference tutorials or other SO answers I can find basically follow this flow. What am I missing?
Electron version: 1.6.2
That's not possible to be working. You didn't wait for value to come in stopReocoring. You need to change your stopRecording function to following:
function stopRecording() {
var save = function() {
console.log(blobs);
toArrayBuffer(new Blob(blobs, {type: 'video/webm'}), function(ab) {
console.log(ab);
var buffer = toBuffer(ab);
var file = `./videos/example.webm`;
fs.writeFile(file, buffer, function(err) {
if (err) {
console.error('Failed to save video ' + err);
} else {
console.log('Saved video: ' + file);
}
});
});
};
recorder.onstop = save;
recorder.stop();
}
This problem literally just fixed itself today without me changing anything. I'm not sure what about my system changed (other than a reboot) but it's now working exactly as it should.

Resources