React-Native : How to rotate base 64 image - react-native

I have PNG image in base64 format which will be saved in server, But before saving into server image need to be rotated.
I have gone through this link, but it doesn't seem possible in react-native.
Is there any way in react-native to rotate base64 image?
I tried using gm package, But i end up with lot of errors in node_modules. Has any one else tried this package?

There is a package react-native-image-rotate
you can rotate any image including base64
Installation
First install the package via npm
$ npm install react-native-image-rotate
then use rnpm to link native libraries
$ react-native link react-native-image-rotate
usage
static rotateImage(
uri: string,
angle: number,
success: (uri: string) => void,
failure: (error: Object) => void
) : void
Example
import React from 'react';
import { StyleSheet, View,Image, TouchableHighlight,Text } from 'react-native';
import ImageRotate from 'react-native-image-rotate';
const string = 'Your base64 image here'
export default class App extends React.Component{
constructor(props){
super(props);
this.state = {
image: string,
currentAngle: 0,
width: 150,
height: 240,
};
this.rotate = this.rotate.bind(this);
}
rotate = (angle) => {
const nextAngle = this.state.currentAngle + angle;
ImageRotate.rotateImage(
string,
nextAngle,
(uri) => {
console.log(uri, 'uri')
this.setState({
image: uri,
currentAngle: nextAngle,
width: this.state.height,
height: this.state.width,
});
},
(error) => {
console.error(error);
}
);
}
render(){
return (
<View style={{flex:1,alignItems:'center'}}>
<Image source={{uri: this.state.image}} style={{width: 300, height: 300}}/>
<TouchableHighlight
onPress={() => this.rotate(90)}
style={styles.button}
>
<Text style={styles.text}>ROTATE CW</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

Here is My research and what i have found https://aboutreact.com/react-native-rotate-image-view-using-animation/
npm install -g react-native-cli
react-native init myproject
cd myproject
then .js
import React from 'react';
import { StyleSheet, View, Animated, Image, Easing } from 'react-native';
export default class App extends React.Component {
RotateValueKeeper: any;
constructor() {
super();
this.RotateValueKeeper = new Animated.Value(0);
}
componentDidMount() {
this.ImageRotateStarterFunction();
}
ImageRotateStarterFunction() {
this.RotateValueKeeper.setValue(0);
Animated.timing(this.RotateValueKeeper, {
toValue: 1,
duration: 3000,
easing: Easing.linear,
}).start(() => this.ImageRotateStarterFunction());
}
render() {
const MyRotateData = this.RotateValueKeeper.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg'],
});
return (
<View style={styles.container}>
<Animated.Image
style={{
width: 150,
height: 150,
transform: [{ rotate: MyRotateData }],
}}
source={{
uri:
'https://aboutreact.com/wp-content/uploads/2018/08/logo1024.png',
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#C2C2C2',
},
});
then
Android
react-native run-android
iOS
react-native run-ios

Related

React Native: Uncaught Error undefined is not an object (evaluating '_reactNativeImagePicker.default.showImagePicker')

I have followed this tutorial to create an image upload app using Firebase and got to the very end and when I build the app using npx react-native run-ios I get this error:
Uncaught Error
undefined is not an object (evaluating
'_reactNativeImagePicker.default.showImagePicker')
Source
29 | }
30 |};
>31 |ImagePicker.showImagePicker(options, respon
|^
32 | if (response.didCancel) {
33 | console.log('User cancelled image picked
34 | } else if (response.error) {
UploadScreen.js (31:5)
This is my UploadScreen.js file:
import React, { useState } from 'react';
import {
View,
SafeAreaView,
Text,
TouchableOpacity,
StyleSheet,
Platform,
Alert,
Image
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import storage from '#react-native-firebase/storage';
import * as Progress from 'react-native-progress';
export default function UploadScreen() {
const [image, setImage] = useState(null);
const [uploading, setUploading] = useState(false);
const [transferred, setTransferred] = useState(0);
const selectImage = () => {
const options = {
maxWidth: 2000,
maxHeight: 2000,
storageOptions: {
skipBackup: true,
path: 'images'
}
};
ImagePicker.showImagePicker(options, response => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
console.log(source);
setImage(source);
}
});
};
const uploadImage = async () => {
const { uri } = image;
const filename = uri.substring(uri.lastIndexOf('/') + 1);
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
setUploading(true);
setTransferred(0);
const task = storage()
.ref(filename)
.putFile(uploadUri);
// set progress state
task.on('state_changed', snapshot => {
setTransferred(
Math.round(snapshot.bytesTransferred / snapshot.totalBytes) * 10000
);
});
try {
await task;
} catch (e) {
console.error(e);
}
setUploading(false);
Alert.alert(
'Photo uploaded!',
'Your photo has been uploaded to Firebase Cloud Storage!'
);
setImage(null);
};
return (
<SafeAreaView style={styles.container}>
<TouchableOpacity style={styles.selectButton} onPress={selectImage}>
<Text style={styles.buttonText}>Pick an image</Text>
</TouchableOpacity>
<View style={styles.imageContainer}>
{image !== null ? (
<Image source={{ uri: image.uri }} style={styles.imageBox} />
) : null}
{uploading ? (
<View style={styles.progressBarContainer}>
<Progress.Bar progress={transferred} width={300} />
</View>
) : (
<TouchableOpacity style={styles.uploadButton} onPress={uploadImage}>
<Text style={styles.buttonText}>Upload image</Text>
</TouchableOpacity>
)}
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
backgroundColor: '#bbded6'
},
selectButton: {
borderRadius: 5,
width: 150,
height: 50,
backgroundColor: '#8ac6d1',
alignItems: 'center',
justifyContent: 'center'
},
uploadButton: {
borderRadius: 5,
width: 150,
height: 50,
backgroundColor: '#ffb6b9',
alignItems: 'center',
justifyContent: 'center',
marginTop: 20
},
buttonText: {
color: 'white',
fontSize: 18,
fontWeight: 'bold'
},
imageContainer: {
marginTop: 30,
marginBottom: 50,
alignItems: 'center'
},
progressBarContainer: {
marginTop: 20
},
imageBox: {
width: 300,
height: 300
}
});
I believe I read that the showImagePicker is no longer in use by the react-native-image-picker package so I think this may be the problem here?
If that is correct then I assume there is a replacement for 'showImagePicker', if so what is it and how can I modify my code to work?
Thank you :)
Edit: I have now implemented launchCamera and launchImageLibrary which allows me to pick a photo from the library but then I get this warning/error? and nothing is uploaded to Firebase....
The import changed in v4, in the tutorial the version is v3 or lesser. yarn add or npm install will always install the latest stable release so you need to check for breaking changes if there is a change in the major version.
https://github.com/react-native-image-picker/react-native-image-picker#methods
There are the new imports
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';
Check this reference of import & export change https://github.com/react-native-image-picker/react-native-image-picker/issues/1746#issuecomment-858670659
From the repo readme
Make sure you're reading the doc applicable to your version, for
example if your using version 3.8.0 go to tag 3.8.0 and read those
docs. This doc is always that of main branch.
Also read version release notes for any breaking changes especially if
you're updating the major version.

Error: Element type is invalid: expected a string (for build-in components) or a class/function... - REACT NATIVE

I got this error while working on my Content.js file:
Before this everything was fine so I know it's not App.js or another file.
I've tried 'npm install' just in case... Most people online that experienced similar errors mention that it might have to do with the way the component is exported but I already changed it to 'export default class Content extends Component' just like most people suggested.
This is the file:
Content.js
import React, { Component } from "react";
import { StyleSheet, View, ActivityIndicator, ScrollView, Card, Text} from 'react-native';
import firebase from '../../firebase';
export default class Content extends Component {
constructor() {
super();
this.state = {
isLoading: true,
article: {},
key: ''
};
}
componentDidMount() {
const ref = firebase.firestore().collection('articles').doc('foo');
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
article: doc.data(),
key: doc.id,
isLoading: false
});
} else {
console.log("No such document!");
}
});
}
render() {
if(this.state.isLoading){
return(
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
)
}
return (
<ScrollView>
<Card style={styles.container}>
<View style={styles.subContainer}>
<View>
<Text h3>{this.state.article.title}</Text>
</View>
<View>
<Text h5>{this.state.article.content}</Text>
</View>
</View>
</Card>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20
},
subContainer: {
flex: 1,
paddingBottom: 20,
borderBottomWidth: 2,
borderBottomColor: '#CCCCCC',
},
activity: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
})
You have imported Card from the react-native but React native does not provide Card component inbuilt.

how to expand a component on click to full screen width and height with animation in reactnative

I have tried to implement the component expand to full screen in react native by using Layout animation in react-native but it was not good to look. Can any one help me in getting it?
changeLayout = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
this.setState({ expanded: !this.state.expanded });
};
I expect to expand the component on click to full screen and again collapse it on click.
Set the initial value you want through the animation, obtain the screen width and height, and create a click function to execute.
This is an example that I made. Click this link if you want to run it yourself.
import React from 'react';
import { Animated, Text, View,Dimensions,Button } from 'react-native';
const screenwidth = Dimensions.get('screen').width
const screenheight = Dimensions.get('screen').height
class FadeInView extends React.Component {
state = {
fadeAnim: new Animated.Value(50),
fadeAnim2: new Animated.Value(50),
}
componentDidMount() {
}
animatebutton() {
Animated.timing( // Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: screenheight,
duration: 10000, // Make it take a while
}
).start();
Animated.timing( // Animate over time
this.state.fadeAnim2, // The animated value to drive
{
toValue: screenwidth,
duration: 10000, // Make it take a while
}
).start(); // Starts the animation
}
render() {
let { fadeAnim,fadeAnim2 } = this.state;
return (
<Animated.View // Special animatable View
style={{
...this.props.style,
height: fadeAnim,
width : fadeAnim2
}}
>
{this.props.children}
</Animated.View>
);
}
}
// You can then use your `FadeInView` in place of a `View` in your components:
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
}
}
animatebutton(){
this.fade.animatebutton();
}
render() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}} >
<FadeInView style={{backgroundColor: 'powderblue'}} ref={ani => this.fade = ani}>
<Text style={{fontSize: 28, textAlign: 'center', margin: 10}}>Fading in</Text>
</FadeInView>
<Button title="go animate" onPress={() => this.animatebutton()}/>
</View>
)
}
}
OR
You can use LayoutAnimation that you want to use. Look at my example.
import React, {Component} from "react";
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
LayoutAnimation,
} from 'react-native';
class App extends Component {
constructor() {
super();
this.state = {
check: false,
}
}
onPresscheck() {
// Uncomment to animate the next state change.
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
// Or use a Custom Layout Animation
// LayoutAnimation.configureNext(CustomLayoutAnimation);
this.setState({ check : !this.state.check});
}
render() {
var middleStyle = this.state.check === false ? {width: 20,height:20} : {width: "100%",height:"100%"};
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={() => this.onPresscheck()}>
<Text>pressbutton</Text>
</TouchableOpacity>
<View style={[middleStyle, {backgroundColor: 'seagreen'}]}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
button: {
width:"100%",
height: 60,
backgroundColor: 'blue',
alignItems: 'center',
justifyContent: 'center',
margin: 8,
},
});
export default App;
Please refer to this blog :
https://dev-yakuza.github.io/en/react-native/react-native-animatable/
Also, try using this library. Use any animation type you want and render them.
Happy coding :)

can't find variable: drawer_width

tried to create side menu in react native, got code from this url https://reactnativeexample.com/simple-lightweight-customisable-menu-drawer-component/
but when i run getting this error: can't find variable: drawer_width
i have tried a lot to solve it but not yet success
Please any one help me
Below is full codes
import React from 'react'
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native'
import MenuDrawer from 'react-native-side-drawer'
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
toggleOpen = () => {
this.setState({ open: !this.state.open });
};
drawerContent = () => {
return (
<TouchableOpacity onPress={this.toggleOpen} style={styles.animatedBox}>
<Text>Close</Text>
</TouchableOpacity>
);
};
render() {
return (
<View style={styles.container}>
<MenuDrawer
open={this.state.open}
drawerContent={this.drawerContent()}
drawerPercentage={45}
animationTime={250}
overlay={true}
opacity={0.4}
>
<TouchableOpacity onPress={this.toggleOpen} style={styles.body}>
<Text>Open</Text>
</TouchableOpacity>
</MenuDrawer>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
marginTop: 30,
zIndex: 0
},
animatedBox: {
flex: 1,
backgroundColor: "#38C8EC",
padding: 10
},
body: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#F04812'
}
})
I think problem is in index.js style sheet is not received DRAWER_WIDTH props
So you can copy this code and customize it and solve its problem
I suggest copy index.js and paste into you code and install prop-types npm
You can replace drawerPercentage into hardcoded value as your requirement into whole code
const DRAWER_WIDTH = SCREEN_WIDTH * (drawerPercentage / 100)
This line write something like this
const DRAWER_WIDTH = SCREEN_WIDTH * (45 / 100)

react native camera undefined

use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class BadInstagramCloneApp extends Component {
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
this.camera.capture()
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('AwesomeProject', () => BadInstagramCloneApp);
I used the following steps to resolve the issue :
Delete the node_modules folder - rm -rf node_modules && npm install
Reset packager cache - rm -fr $TMPDIR/react-* or node_modules/react-native/packager/packager.sh --reset-cache
Clear watchman watches - watchman watch-del-all
Recreate the project from scratch
But i still get an error.
Make sure you have made the settings right, including running $ react-native link react-native-camera and others according the documentation.
You can try to use
var Camera = require('react-native-camera')
Replace the line:
import Camera from 'react-native-camera';
With this line:
import {RNCamera} from 'react-native-camera';
Change <Camera></Camera> tag to <RNCamera></RNCamera>.
Remove the aspect attribute from RNCamera tag.