React-Native-Camera get height and width from uri - react-native

I have an app, which takes a photo and add it to the pdf file. Problem is resizing. I can resize it with pixels, but that not keep the original ratio. I need original height and width for calculating the right size
Calculate: Divide height by width, example 1200/1600 = 0,75. Then we can resize pd image height 100px and width is 100 / 0,75.
Question is: How can I get the size of image (data.uri)?
My code:
takePicture = async() => {
if (this.camera) {
const options = { quality: 0.5, base64: true , fixOrientation: true}; // Option for wuality etc
const data = await this.camera.takePictureAsync(options); // Take the image
console.log(data.uri); // Prints image (data) address to console log
back(data.uri) // Go back to ReportFault page
}
};
let imgX = 297;
let imgY = 618;
page.drawImage(arr[i].path.substring(7),'jpg',{
x: imgX, // Position in pdf A4
y: imgY, // Position in pdf A4
width: 200,
height: 150,
})

you can use react native Image getSize method
try this
import { Image } from 'react-native';
.....
Image.getSize(uri, (width, height) => {
console.log(`The image dimensions are ${width}x${height}`);
}, (error) => {
console.error(`Couldn't get the image size: ${error.message}`);
});

Related

issue in image to PDF not working in react native

I am trying to generate PDF from image path in react native so i am using below plugin for that
https://www.npmjs.com/package/react-native-image-to-pdf/v/1.2.0
As per above doc i configure all the thing and below is my code
const myAsyncPDFFunction = async () => {
try {
console.log('Call a');
let path ='file:///Users/macminiharshalk/Library/Developer/CoreSimulator/Devices/FADDF530-05FD-4A0E-9E61-C6AEDB719955/data/Containers/Data/Application/37B8FE42-B23A-4018-865F-F57670B3411E/tmp/606C88B3-5759-4942-A544-1231A0C17532.jpg';
const options = {
imagePaths: [path],
name: 'PDFName',
maxSize: {
// optional maximum image dimension - larger images will be resized
width: 900,
height: Math.round(
(Dimensions.get('window').height / Dimensions.get('window').width) *
900,
),
},
quality: 0.7, // optional compression paramter
// targetPathRN: "/storage/emulated/0/Download/", // only for android version 9 and lower
//for versions higher than 9 it is stored in (Download/img-to-pdf/)
};
console.log("options-->", options);
const pdf = await RNImageToPdf.createPDFbyImages(options);
console.log('PDF URIs-->', pdf);
console.log(pdf.filePath);
} catch (e) {
console.log(e);
}
};
When i console log i can able to see pdf path as below
/Users/macminiharshalk/Library/Developer/CoreSimulator/Devices/FADDF530-05FD-4A0E-9E61-C6AEDB719955/data/Containers/Data/Application/37B8FE42-B23A-4018-865F-F57670B3411E/Documents/PDFName.pdf
When i console option parameter it is showing as below
{"imagePaths": ["file:///Users/macminiharshalk/Library/Developer/CoreSimulator/Devices/FADDF530-05FD-4A0E-9E61-C6AEDB719955/data/Containers/Data/Application/37B8FE42-B23A-4018-865F-F57670B3411E/tmp/606C88B3-5759-4942-A544-1231A0C17532.jpg"], "maxSize": {"height": 1948, "width": 900}, "name": "PDFName", "quality": 0.7}
But when i open PDF image is not copy it is blank PDF so any idea how can i show image in PDF ?
please try
const newPath = path.replace('file://', ​​'');

react-native-image-crop-picker is Compressing the image before cropping

I have implemented this library. But on android only the image is being compressed when picking the image. For example, If I select like a large image 9921x4961 exactly and then log its width and height after being picked it will be 1241x621 which divided by 8 exactly. And this issue only appears on android.
Here is my implementation:
const res = await ImagePicker.openPicker({
multiple: true,
mediaType: 'any',
compressVideoPreset: 'HighestQuality',
maxFiles: 10
})
for await (const image of res) {
Image.getSize(image.path, async (width, height) => {
console.log('SIZE-PICKER: ', { width, height });
await cropAndAttachImage(image);
});
}
Set compressImageQuality: 1 in options.
If it still does not help, solution is to set a greater height/width manually.
const res = await ImagePicker.openPicker({
width: 2048, // or something else depending on your use case
height: 1024, // same as above
compressImageQuality: 1,
....
})
You can also set width / height x times viewport.
Similar issues #1356, #1085

React Native & Expo - onContextCreate function not calling when application ran

I don't know why and there is no error shown in debugger-ui. I only see white screen in my iphone with no errors. I also add a console.log inside onContextCreate function and there is no message, so it means onContextCreate function not triggered and here is my code. Any help is very helpful.
import { View as GraphicsView } from 'expo-graphics';
import ExpoTHREE, { THREE } from 'expo-three';
import React from 'react';
export default class App extends React.Component {
UNSAFE_componentWillMount() {
THREE.suppressExpoWarnings();
}
render() {
// Create an `ExpoGraphics.View` covering the whole screen, tell it to call our
// `onContextCreate` function once it's initialized.
return (
<GraphicsView
style={{backgroundColor: 'yellow'}}
onContextCreate={this.onContextCreate}
onRender={this.onRender}
/>
);
}
// This is called by the `ExpoGraphics.View` once it's initialized
onContextCreate = async ({
gl,
canvas,
width,
height,
scale: pixelRatio,
}) => {
console.log('onContextCreate ran...');
this.renderer = new ExpoTHREE.Renderer({ gl, pixelRatio, width, height });
this.renderer.setClearColor(0xffffff)
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
this.camera.position.z = 5;
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshPhongMaterial({
color: 0xff0000,
});
this.cube = new THREE.Mesh(geometry, material);
this.scene.add(this.cube);
this.scene.add(new THREE.AmbientLight(0x404040));
const light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.set(3, 3, 3);
this.scene.add(light);
};
onRender = delta => {
this.cube.rotation.x += 3.5 * delta;
this.cube.rotation.y += 2 * delta;
this.renderer.render(this.scene, this.camera);
};
}
I realized that when i close remote debugger in EXPO than my codes are working. This is why happened i don't know. It is good to someone else explain it but it works when i close remote debugging in EXPO...

Save Sketched lines in LocalStorage

Sorry im posting this here
I want to save the info of each line i drew on canvas(the save action would be called onChange)
so i can retrieve this data and draw it on canvas again in case the user change screen or something.
I'm using expo-pixi to draw a image and sketch over it
onChangeAsync = async (param) => {
// here i want on change code i get the line informantion and store it
}
onLayout = async ({
nativeEvent: {
layout: { width, height },
},
}) => {
this.setState({
layoutWidth: width,
layoutHeight: height,
})
this.onReady();
}
onReady = async () => {
const { layoutWidth, layoutHeight, points } = this.state;
this.sketch.graphics = new PIXI.Graphics();
if (this.sketch.stage) {
if (layoutWidth && layoutHeight) {
const background = await PIXI.Sprite.fromExpoAsync(this.props.image);
background.width = layoutWidth * scaleR;
background.height = layoutHeight * scaleR;
this.sketch.stage.addChild(background);
this.sketch.renderer._update();
}
}
};
// The sketch component is pretty much as the example which comes with the lib
<Sketch
ref={ref => (this.sketch = ref)}
style={styles.sketch}
strokeColor={this.state.strokeColor}
strokeWidth={this.state.strokeWidth}
strokeAlpha={1}
onChange={this.onChangeAsync}
onReady={this.onReady}
/>
Does anyone have any clue? im kind of desperate
Thanks

Invalid imageTag error from ImageStore.getBase64ForTag

I am trying to get a base64 image from facebook profile picture.
getImageFromFacebook() {
const imageURL = this.props.userInfo.picture;
Image.getSize(imageURL, (width, height) => {
var imageSize = {width, height};
ImageEditor.cropImage(imageURL, imageSize, (imageURI) => {
console.log(imageURI);
ImageStore.getBase64ForTag(imageURI, (base64Data) => {
this.setState({pictureBase64: base64Data});
ImageStore.removeImageForTag(imageURI);
}, (reason) => console.log(reason) )
}, (reason) => console.log(reason) )
}, (reason) => console.log(reason))
}
I am following the steps described in this https://github.com/facebook/react-native/issues/1158:
Use Image.getSize(uri) to get the image dimensions.
Use ImageEditor.cropImage(uri, cropData) to store a copy of the image in the ImageStore (if you pass the width and height you got in step 1) then cropImage won't actually crop the image, although it may still make a copy of it.
Use ImageStore.getBase64ForTag(uri) to get the base64 data of the new image (pass the uri you got from the cropImage function, not the original).
Don't forget to call ImageStore.removeImageForTag(uri) once you're done to delete the copy.
Although the ImageEditor.cropImage returns a valid URI (rct-image-store://0), ImageStore.getBase64ForTag fails with a reason:
code: "ERCTERRORDOMAIN0",
domain: "RCTErrorDomain",
message: "Invalid imageTag: rct-image-store://0"
What am I doing wrong?
Found the error!
imageSize should be set like this:
var imageSize = {
size: {
width,
height
},
offset: {
x: 0,
y: 0,
},
};