I Want to capture multiple images using react-native-image-picker - javascript

// add no of images equal to Qty
handleQuantity(qty) {
this.setState({ qty: qty })
for (let i = 0; i < qty; i++) {
this.selectPhotoTapped(i)
}
}
selectPhotoTapped(count) {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true
}
};
ImagePicker.launchCamera(options, (response) => {
console.log(response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else {
//let source = { uri: response.uri };
// this.setState({
// ImageSourceArr: [...this.state.ImageSourceArr, source]
// });
Realm.open(databaseOptions).then(realm => {
realm.write(() => {
realm.create(Images_SCHEMA, {
id: count,
path: response.uri
});
// this.setState({ size: realm.objects(Images_SCHEMA).length });
const res = realm.objects(Images_SCHEMA)
let res2 = JSON.parse(JSON.stringify(res))
for (let key in res2) {
this.setState({
ImageSourceArr: [...this.state.ImageSourceArr, res2[key].path],
size: realm.objects(Images_SCHEMA).length
});
}
});
});
}
});
}
handleQuantity() function call no of quantity times selectedPhototap() function
and selectedPhotoTap() function insert path into realm , but the problem is that it store only last image path,i want to insert all images that capture by function selectedPhotoTap
Please anybody help me

react-native-image-picker does not support for multiple image selection, crop tool, and landscape support for native iOS functionality - not issues with the library. If you need these things, react-native-image-crop-picker might be a better choice for you.
https://github.com/ivpusic/react-native-image-crop-picker

Related

set timer inside a loop for graphql query

The thing I'm doing here is fetching anime characters from anilist graphql api. The reason I've added a loop is so I could fetch data from a certain character id to a limit. For example 1-100. But I want to respect their API rate limits and so I'd like a way to limit my requests to 1 per second. Hence, I've used setTimeout, but I still got rate-limited from the API and using setInterval only keeps on looping it every 5 seconds. Like the same data gets fetched every 5 seconds.
Is there any way I can make it as I've mentioned?
My code:
const fs = require("fs");
const number = 3;
const axios = require("axios");
async function fetchData() {
for (let i = 1; i <= number; i++) {
const query = axios
.post(
"https://graphql.anilist.co",
{
query: `query character(
$id: Int
$page: Int
$sort: [MediaSort]
$onList: Boolean
$withRoles: Boolean = false
) {
Character(id: $id) {
id
name {
first
middle
last
full
native
userPreferred
alternative
alternativeSpoiler
}
image {
large
}
favourites
isFavourite
isFavouriteBlocked
description
age
gender
bloodType
dateOfBirth {
year
month
day
}
media(page: $page, sort: $sort, onList: $onList) #include(if: $withRoles) {
pageInfo {
total
perPage
currentPage
lastPage
hasNextPage
}
edges {
id
characterRole
voiceActorRoles(sort: [RELEVANCE, ID]) {
roleNotes
voiceActor {
id
name {
userPreferred
}
image {
large
}
language: languageV2
}
}
node {
id
type
isAdult
bannerImage
title {
userPreferred
}
coverImage {
large
}
startDate {
year
}
mediaListEntry {
id
status
}
}
}
}
}
}`,
variables: {
id: i,
withRoles: false,
},
},
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => {
// console.log(response.data.data.Character)
const jsonContent =
JSON.stringify(response.data.data.Character, null, 4) + ", ";
fs.appendFile("./chars.json", jsonContent, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
})
.catch((error) => console.log(`Code: ${error}`, error));
}
}
fetchData();
Something like that will work for you (Asuming all the rest was ok):
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function fetchData() {
for (let i = 1; i <= number; i++) {
// So in case your function is called in loop - request will be delayed
await delay(5000); // TODO: Change to whatever you need
const query = axios.post(
"https://graphql.anilist.co",
{
query: someQuery, // TODO: Set your query here
variables: { id: i, withRoles: false }
},
{
headers: { "Content-Type": "application/json" }
}
);
try {
const response = await query;
const jsonContent = JSON.stringify(response.data.data.Character, null, 4) + ", ";
fs.appendFile("./chars.json", jsonContent, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
} catch (e) {
console.log(`Code: ${e}`, e);
}
}
}

Node.js JIMP restarting app after file was saved

I have such a small app where I am using JIMP. My goal here is to add a watermark on a jpeg file. The main part of my app is working fine, but I want to add a "Retry" function for users. Now, this part is not working. Retry part is called before my edited file was saved
const Jimp = require('jimp');
const inquirer = require('inquirer');
const fs = require('fs');
const addTextWatermarkToImage = async function(inputFile, outputFile, text) {
try {
const image = await Jimp.read(inputFile);
const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK);
const textData = {
text: text,
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE,
};
image.print(font, 10, 10, textData, image.getWidth(), image.getHeight());
image.quality(100).write(outputFile);
} catch (error) {
console.log('Error. Something went wrong');
}
};
const addImageWatermarkToImage = async function(
inputFile,
outputFile,
watermarkFile
) {
try {
const image = await Jimp.read(inputFile);
const watermark = await Jimp.read(watermarkFile);
const x = image.getWidth() / 2 - watermark.getWidth() / 2;
const y = image.getHeight() / 2 - watermark.getHeight() / 2;
image.composite(watermark, x, y, {
mode: Jimp.BLEND_SOURCE_OVER,
opacitySource: 0.5,
});
image.quality(100).write(outputFile);
} catch (error) {
console.log('Error. Something went wrong');
}
};
const prepareOutputFilename = filename => {
const [name, ext] = filename.split('.');
return `${name}-with-watermark.${ext}`;
};
const startApp = async () => {
//check if user is ready
const answer = await inquirer.prompt([
{
name: 'start',
message:
'Hi! This is "Watermar manager". Move your files to `/img` folder. Then you\'ll be able to use them in the app. Are you ready?',
type: 'confirm',
},
]);
// if no - exit app
if (!answer.start) process.exit();
// ask about input file and watermark type
const options = await inquirer.prompt([
{
name: 'inputImage',
type: 'input',
message: 'What file do you want to mark?',
default: 'test.jpg',
},
{
name: 'watermarkType',
type: 'list',
choices: ['Text watermark', 'Image watermark'],
},
]);
if (options.watermarkType === 'Text watermark') {
const text = await inquirer.prompt([
{
name: 'value',
type: 'input',
message: 'Type your watermark text:',
},
]);
options.watermarkText = text.value;
if (fs.existsSync('./img/' + options.inputImage) === true) {
addTextWatermarkToImage(
'./img/' + options.inputImage,
'./img/' + prepareOutputFilename(options.inputImage),
options.watermarkText
);
} else {
console.log('O_o Error!!!! No such file');
}
} else {
const image = await inquirer.prompt([
{
name: 'filename',
type: 'input',
message: 'Type your watermark name:',
default: 'logo.png',
},
]);
options.watermarkImage = image.filename;
if (
fs.existsSync('./img/' + options.inputImage) === true &&
fs.existsSync('./img/' + options.watermarkImage) === true
) {
addImageWatermarkToImage(
'./img/' + options.inputImage,
'./img/' + prepareOutputFilename(options.inputImage),
'./img/' + options.watermarkImage
);
} else {
console.log('O_o Error!!!! No such file');
}
}
console.log('File was saved - now');
const retry = await inquirer.prompt([
{
name: 'retry',
message: 'Do you want to try again',
type: 'confirm',
},
]);
if (!retry.retry) process.exit();
startApp();
};
startApp();
I want to re-run this app after my file was saved. Right now
const retry = await inquirer.prompt([
{
name: 'retry',
message: 'Do you want to try again',
type: 'confirm',
},
]);
if (!retry.retry) process.exit();
startApp();
this part of my code runs before my file was saved and this can casue some problems.
Any suggestions on how to deal with this issue?
You are calling few async method with out using await statement (addImageWatermarkToImage, addImageWatermarkToImage). use await and check the same.
//Consider the following example. Execute the test method with and with out awit, it may help you to understood
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function sleep(fn, ...args) {
await timeout(3000);
return fn(...args);
}
async function test() {
//add and remove the below await and execute this function
await sleep(()=>{console.log("Run first")},{});
console.log("Run Second");
}
test();

Firebase/Ionic4 upload and Crop Images to storage

Heyy, i am trying to upload a cropped image to firebase.
I would prefer to use the ionic native "image-picker" and "Crop".
I really dont know how to upload the image after cropping it, because it only returns the path of the new image.
I have already tryed something like this. This worked, but i was not able to crop the image. But as i mentioned, i would prefer using the native tools anyways.
export interface UploadData {
name: string;
filepath: string;
size: number;
}
uploadFile(event: FileList) {
// The File object
const file = event.item(0);
// Validation for Images Only
if (file.type.split('/')[0] !== 'image') {
console.error('unsupported file');
return;
}
// The storage path
const path = `whatever/${new Date().getTime()}_${file.name}`;
// File reference
const fileRef = this.storage.ref(path);
// The main task
this.task = this.storage.upload(path, file, { customMetadata });
this.snapshot = this.task.snapshotChanges().pipe(
finalize(() => {
// Get uploaded file storage path
this.UploadedFileURL = fileRef.getDownloadURL();
this.UploadedFileURL.subscribe(resp => {
this.addImagetoDB({
name: file.name,
filepath: resp,
size: this.fileSize
});
}, error => {
console.error(error);
});
}),
tap(snap => {
this.fileSize = snap.totalBytes;
})
);
}
addImagetoDB(image: UploadData) {
const id = this.db.createId();
// Set document id with value in database
this.imageCollection.doc(id).set(image).then(resp => {
console.log(resp);
}).catch(error => {
console.log('error ' + error);
});
}
}
This is how i would like to do it. But i really have no idea, how to upload it at this point.
pickImage() {
this.imagePicker.getPictures(this.imagePickerOptions).then((results)
=> {
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < results.length; i++) {
this.cropImage(results[i]);
}
}, (err) => {
alert(err);
});
}
cropImage(imgPath) {
this.crop.crop(imgPath, { quality: 50 })
.then(
newPath => {
// ?????
},
error => {
alert('Error cropping image' + error);
}
);
}
Sorry, i am very new to this stuff.
Thanks for your help :)
It seems that you might be able to do this without the crop feature being needed.
These are the options according to the docs:
options = {
// Android only. Max images to be selected, defaults to 15. If this is set to 1, upon
// selection of a single image, the plugin will return it.
maximumImagesCount: int,
// max width and height to allow the images to be. Will keep aspect
// ratio no matter what. So if both are 800, the returned image
// will be at most 800 pixels wide and 800 pixels tall. If the width is
// 800 and height 0 the image will be 800 pixels wide if the source
// is at least that wide.
width: int,
height: int,
// quality of resized image, defaults to 100
quality: int (0-100),
// output type, defaults to FILE_URIs.
// available options are
// window.imagePicker.OutputType.FILE_URI (0) or
// window.imagePicker.OutputType.BASE64_STRING (1)
outputType: int
};
So you could use:
options = {
maximumImagesCount: 3,
width: 800,
height: 600,
quality: 50,
outputType: 1
};
From what I've been researching you could then put the image into Firebase Storage using:
storageRef.putString("Your base64 string substring variable", 'base64');
I'm not sure if this is enough to get you fixed up but I thought I would post what I had found anyway.
I just tried this, but it dosnĀ“t work too. I have no idea why...
constructor(private imagePicker: ImagePicker, private crop: Crop,
private file: File) {
let storageDb = firebase.storage();
this.storageRef = storageDb.ref();
}
pickImage() {
this.imagePicker.getPictures(this.imagePickerOptions).then((results)
=> {
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < results.length; i++) {
this.cropImage(results[i]);
}
}, (err) => {
alert(err);
});
}
cropImage(imgPath) {
this.crop.crop(imgPath, { quality: 50 })
.then(
newPath => {
try {
let n = newPath.lastIndexOf("/");
let x = newPath.lastIndexOf("g");
let nameFile = newPath.substring(n + 1, x + 1);
this.file.readAsArrayBuffer(newPath, nameFile).then((res) => {
let blob = new Blob([res], { type: "image/jpeg" });
var uploadTask = this.storageRef.child('images/' + this.event.id).put(blob);
uploadTask.on('state_changed', (snapshot) => {
let url = uploadTask.snapshot.downloadURL;
this.croppedImagepath = url;
}, (error) => {
alert("error: " + error);
}, () => {
alert("uploaded");
let url = uploadTask.snapshot.downloadURL;
this.croppedImagepath = url;
})
})
}
catch (z) {
alert('error beim erstellen des blobs' + z);
}
},
error => {
alert('Error cropping image' + error);
}
);
}

How to get push key in firebase?

I want to get the Key generated when I push data to Firebase database. I want to handle them with my own function,
So the issue is when the user fills the form he sends the data to our real-time DB, contained in this data are some images (optional), and I don't need to let the image object empty in DB, so how to handle this, and when the user needs to send an image I want to save this image in the same Order, not in New Order.
Node
Here is my function
handleOrder = () => {
const { nameOfProblem, description, userId, imageOfPrblem, providerId } = this.state;
const PushData = firebase.database().ref("request/" + providerId + "/" + userId + "/orders/");
const ref = firebase.storage().ref("users/" + userId + "/UserImageOrders/" + path);
let file = imageOfPrblem.uri;
const path = "img_" + imageOfPrblem.fileName;
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({ // didn't updated the key generated just add new element with new key !!
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
}
handleImages = () => {
const options = {
title: "Select Images!",
storageOptions: {
skipBackup: true,
path: "images"
}
};
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.uri) {
this.setState({ imageOfPrblem: 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);
alert(response.customButton);
}
});
};
This seems to work fine for me:
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
console.log("new key: "+newChildRef.key);
ref.child(newChildRef.key).update({ secondChild: true });
After running this code, I end up with this JSON in the new child whose key gets logged:
"-LdgLWu_wBNNicFlPDGj" : {
"firstChild" : true,
"secondChild" : true
}
Live demo: https://jsbin.com/hovoleh/edit?js,console
Live JSON: https://stackoverflow.firebaseio.com/55912103.json?print=pretty
Update: if you just want to write both the existing data and new data to a new location:
var newOrderRef = PushData.push({
nameOfProblem: nameOfProblem,
description: description,
});
if (file) {
let keyG = newOrderRef.key; // Key Generated with .push()
PushData.child(keyG).update({
nameOfProblem: nameOfProblem,
description: description,
imageOfPrblem: imageOfPrblem
});
ref.put(file).then(() => {
console.log("File uploaded..")
});
}
The push ID from any Firebase snapshot ref is in ref.name().
I know it's been a while since the author created a post but maybe someone will find it useful.
The above answers are a bit wrong because, for example, after: newChildRef
var ref = firebase.database().ref("/55912103");
var newChildRef = ref.push({ firstChild: true });
newChildRef <--- promise
ref = rdb.ref('name_of_your_ref');
var childRef = ref.push({
IdUser: currentUserId,
ProductCategory: pCategory,
ProductDescription: pDesc,
ProductId: pId,
ProductName: pName,
ProductPrice: pPrice,
ProductQuantity: pQuan
}).catch(err => console.log(err.message));
childRef.then(item => {
ref.child(item.key).update({
IdKey: item.key
}).then(() => history.push('/delivery/basket'));
});
Greetings, Matthew

React-native-fbsdk ShareDialog. How to share with prefilled message and photos content together?

I have react-native 0.44.0 and react-native-fbsdk 0.5.0. ShareDialog component work fine, but due to lack of docs explanation had been totally stuck. I have app with own API. I make API call fetch sharing template with photos array.
.then((responseData) => {
console.log("Facebook Share Api Test")
console.log(responseData)
// After receiving result checking Platform
// If this is iOS we should let our result image links be fetched to encode it in Base64.
if(Platform.OS !== 'android'){
console.log("Not Andro!d!")
let imgUrl
let sharePhotoContent
let iteratePhotos = function (data) {
var photoInfo = [];
var ready = Promise.resolve(null)
data.forEach(function (value, i) {
let iconURL = API.SERVER_URL + API.SERVICE_PORT + API.HEAD_ICON_RES_URL + value.photo_id + 'S'
ready = ready.then(function () {
return RNFetchBlob
.fetch('GET', iconURL)
.then(res => res.data)
.then(resData => {
imgUrl = 'data:image/jpeg;base64,' + resData
console.log(imgUrl)
return imgUrl
})
.then(img => {
console.log(img)
let res = {
imageUrl: img,
userGenerated: true,
caption: value.comment
}
return res
})
.catch(err => {
console.log(err)
})
}).then(function (resData) {
photoInfo[i] = resData;
});
});
return ready.then(function () { return photoInfo; });
}
iteratePhotos(responseData.photos).then((res) => {
console.log('res', res)
if(res.length > 0){
sharePhotoContent = {
contentType: 'photo',
contentDescription: 'Wow, check out this great site!',
photos: res
}
} else {
sharePhotoContent = {
contentType: 'link',
contentUrl: 'some url',
message: responseData.message
}
}
ShareDialog.canShow(sharePhotoContent)
.then((canShow) => {
if (canShow) {
return ShareDialog.show(sharePhotoContent);
}
})
.then((result) => {
this.setState({isshowIndicator: false})
if(!result.isCancelled){
this.setState({isFacebookShared: true})
setTimeout(() => alert("Success!"), 100)
}
})
.catch(error => {
this.setState({isshowIndicator: false})
console.log(error)
setTimeout(() => alert('Share fail with error: ' + error), 100)
}
)
})
} else {
let photoInfo = responseData.photos.map(value => {
return {
imageUrl: API.SERVER_URL + API.SERVICE_PORT + API.HEAD_ICON_RES_URL + value.photo_id + 'S',
...value
}
})
console.log(photoInfo, "It IS ANDROID")
if(responseData.photos.length > 0){
var sharePhotoContent = {
contentType: 'photo',
photos: photoInfo
}
} else {
var sharePhotoContent = {
contentType: 'link',
contentUrl: 'some url',
message: responseData.message
}
}
ShareDialog.canShow(sharePhotoContent)
.then((canShow) => {
if (canShow) {
return ShareDialog.show(sharePhotoContent);
}
})
.then((result) => {
this.setState({isshowIndicator: false})
if(!result.isCancelled){
this.setState({isFacebookShared: true})
setTimeout(() => alert("Success!"), 100)
}
})
.catch(error => {
this.setState({isshowIndicator: false})
setTimeout(() => alert('Share fail with error: ' + error), 100)
})
}
})
When I tap share, sharedialog opens and photos that I want are pasted but message line waits to be filled
But I need into ShareDialog opened:
Photos needed to be attached;
Message to be prefilled according that one I received from my API.
Is this possible? Please help this is prerelease feature needed to be implemented very fast and I havent any idea how((
Attaching screenshots that describes 1. what is going now here? 2. What i want to do.
some social network like facebook does not support pre-filling the message for users as seen in their Policy: https://developers.facebook.com/policy/#socialplugins

Categories

Resources