How not to save images in cache - android

I want to save images using Camera in angular but the image always saves in the cache folder off my app :
http://localhost/_app_file_/storage/emulated/0/Android/data/io.ionic.starter/cache/my_image.jpeg
Here is the code to take a picture :
image: any = '';
async openCam() {
const options: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.NATIVE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
};
try {
const imageData = await this.camera.getPicture(options);
return this.image = (window as any).Ionic.WebView.convertFileSrc(imageData);
} catch (err) {
// Handle error
if (JSON.stringify(err) !== '"No Image Selected"') {
alert('error ' + JSON.stringify(err));
}
}
}
Here is the code to save and get the image :
async saveItem(item, value, secondValue) {
this.nativeStorage.setItem(item, { one: value, two: secondValue })
.then(() => console.log('Stored item!'))
.catch(error => console.error('Error storing item', error));
}
async getItem(item) {
return await this.nativeStorage.getItem(item);
}
I want to be able to store the image in the file of the app not in the cache
Ty for your responses

Related

I'm getting 'undefined is not an object (near '...}).fs.writeFile(' when trying to download base64 image png in react native React Native

Here is my code:
const saveImg = async (base64Img: string, success: Function, fail:Function) => {
const isAndroid = Platform.OS === "android"
const isIos = Platform.OS === 'ios'
const dirs = isIos? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath;
const certificateTitle = 'certificate-'+((Math.random() * 10000000) | 0)
const downloadDest = `${dirs}/${certificateTitle}.png`;
const imageDatas = base64Img.split('data:image/png;base64,');
const imageData = imageDatas[1];
try{
await RNFetchBlob.config({
addAndroidDownloads:{
notification:true,
description:'certificate',
mime:'image/png',
title:certificateTitle +'.png',
path:downloadDest
}
}).fs.writeFile(downloadDest, imageData, 'base64')
if (isAndroid) {
} else {
RNFetchBlob.ios.previewDocument(downloadDest);
}
success()
}catch(error:any){
console.log(error)
fail()
}
}
I get this error:
undefined is not an object (near '...}).fs.writeFile(downloadD...')
at node_modules/react-native-webview/lib/WebView.android.js:207:16 in _this.onMessage
When I hit the download button and this runs I get the mentioned Error.
I use to get the download done with the below code modification, but I really need to show the download feedback from both android and IOS.
This works (but without notification)
await RNFetchBlob.fs.writeFile(downloadDest, imageData, 'base64')
I am using expo
I discovered that the react-fetch-blob does not work with expo, to solve it, I used the following libraries:
expo-file-system, expo-media-library, expo-image-picker,expo-notifications
This was the code to convert, download and show the notification of the image in the "expo way":
import * as FileSystem from 'expo-file-system';
import * as MediaLibrary from 'expo-media-library';
import * as ImagePicker from 'expo-image-picker';
import * as Notifications from 'expo-notifications';
const saveImg = async (base64Img: string, success: Function, fail:Function) => {
const imageDatas = base64Img.split('data:image/png;base64,');
const imageData = imageDatas[1];
try {
const certificateName = 'certificate-'+((Math.random() * 10000000) | 0) + ".png"
const certificatePathInFileSystem = FileSystem.documentDirectory +certificateName ;
await FileSystem.writeAsStringAsync(certificatePathInFileSystem, imageData, {
encoding: FileSystem.EncodingType.Base64,
});
await MediaLibrary.saveToLibraryAsync(certificatePathInFileSystem);
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: true,
}),
});
await Notifications.scheduleNotificationAsync({
content: {
title: certificateName +' saved !',
body: "Click to show the certificate",
},
trigger: null,
});
setCertificatePath(certificatePathInFileSystem)
success()
} catch (e) {
console.error(e);
fail()
}
}
In order to open the images gallery on click I used this code:
useEffect(()=>{
if(certificatePath){
Notifications.addNotificationResponseReceivedListener( async (event )=> {
await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
})
})
}
},[certificatePath])
Try to call fetch after create RNFetchBlob.config
If you just wanna display an Image and not store you can show image as fallows (https://reactnative.dev/docs/next/images#uri-data-images)
<Image
style={{
width: 51,
height: 51,
resizeMode: 'contain'
}}
source={{
uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='
}}
/>
Call fetch on config object:
try{
const fetchConfig = await RNFetchBlob.config({
addAndroidDownloads:{
notification:true,
description:'certificate',
mime:'image/png',
title:certificateTitle +'.png',
path:downloadDest
}
})
fetchConfig.fetch('your.domain.com').fs.writeFile(downloadDest, imageData, 'base64')
if (isAndroid) {
} else {
RNFetchBlob.ios.previewDocument(downloadDest);
}
success()
}catch(error:any){
console.log(error)
fail()
}

ionic 4 (android) get image (OBJECT FILE) from gallery (FILE_URI) and upload via API

I'm trying to implement a simple application using Ionic v4 angular and cordova. Just select a photo and upload it to a parse server (back4app.com). But I couldn't do it.
This is my code:
home.page.ts
import { ParseService } from '../service/parse.service';
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import { File } from '#ionic-native/file/ngx';
import { WebView } from '#ionic-native/ionic-webview/ngx';
selectPhoto() {
const options: CameraOptions = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
correctOrientation: true
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
// let base64Image = 'data:image/jpeg;base64,' + imageData;
// console.log(imageData);
this.fileToUpload = imageData;
this.phototoshow = this.webview.convertFileSrc(imageData);
}, (err) => {
// Handle error
});
}
onSubmit() {
this.presentLoading();
// return this.apiService.upload(this.phototoshow).subscribe((data: any) => {
return this.apiService.upload(this.fileToUpload).subscribe((data: any) => {
console.log(data);
}
}
service.ts
upload(img1): Observable<any> {
// console.log(data);
return this.http.post(this.apiURL + '/files/img.jpg', img1,{
headers: {
'X-Parse-Application-Id': this.APP_ID,
'X-Parse-REST-API-Key': this.REST_API_KEY,
'Content-Type':'image/jpeg'
}
})
.pipe(
retry(1),
catchError(this.handleError)
)
}
I was able to upload the image with "input type = file" in the form ... but selecting the image from the gallery with the cordova plugin camera ... it only returns FILE_URI but I need the OBJECT FILE to upload via api rest.
I have read enough info on the web but it is old information that does not help me. I hope someone can help me with the problem. thanks
I managed to solve the problem:
startUpload() {
this.file.resolveLocalFilesystemUrl(this.fileToUpload)
// this.file.resolveLocalFilesystemUrl(imgEntry.filePath)
.then(entry => {
(entry as FileEntry).file(file => this.readFile(file))
})
.catch(err => {
alert('Error while reading file.');
});
}
readFile(file: any) {
const reader = new FileReader();
reader.onload = () => {
const imgBlob = new Blob([reader.result], {
type: file.type
});
this.onSubmit(imgBlob);
};
reader.readAsArrayBuffer(file);
}

Saving a photo taking a very long time

I want users to be able to take photos from within my app and have the photos save to their gallery (so that I can later view them in a photo-picker).
I have the following code from react-native-camera, it's basically the bare-bones demo code.
takePicture() {
const options = { quality: 0.5, fixOrientation: false, width: 1920 };
if (this.camera) {
this.camera
.takePictureAsync(options)
.then(data => {
this.saveImage(data.uri);
})
.catch(err => {
console.error("capture picture error", err);
});
} else {
console.error("No camera found!");
}
}
}
To move the attachment, I am using react-native-fs, as follows (more basic demo-y code):
const dirHome = Platform.select({
ios: `${RNFS.DocumentDirectoryPath}/Pictures`,
android: `${RNFS.ExternalStorageDirectoryPath}/Pictures`
});
const dirPictures = `${dirHome}/MyAppName`;
saveImage = async filePath => {
try {
// set new image name and filepath
const newImageName = `${moment().format("DDMMYY_HHmmSSS")}.jpg`;
const newFilepath = `${dirPictures}/${newImageName}`;
// move and save image to new filepath
const imageMoved = await this.moveAttachment(filePath, newFilepath);
console.log("image moved: ", imageMoved);
} catch (error) {
console.log(error);
}
};
moveAttachment = async (filePath, newFilepath) => {
return new Promise((resolve, reject) => {
RNFS.mkdir(dirPictures)
.then(() => {
RNFS.moveFile(filePath, newFilepath)
.then(() => {
console.log("FILE MOVED", filePath, newFilepath);
resolve(true);
})
.catch(error => {
console.log("moveFile error", error);
reject(error);
});
})
.catch(err => {
console.log("mkdir error", err);
reject(err);
});
});
};
When taking a photo, this code executes and prints that the image has been moved within a couple of seconds. But, when I look into the built in Gallery App on the device, it often takes several minutes for the image to finally load. I've tried this across many different devices, both emulated and physical... am I doing something wrong? Thanks!
This was caused by Android's Media Scanner not immediately realizing new files existed.
From this Git issue and the subsequent PR: https://github.com/itinance/react-native-fs/issues/79
I modified my code as follows:
saveImage = async filePath => {
try {
// set new image name and filepath
const newImageName = `${moment().format("DDMMYY_HHmmSSS")}.jpg`;
const newFilepath = `${dirPicutures}/${newImageName}`;
// move and save image to new filepath
const imageMoved = await this.moveAttachment(filePath, newFilepath).then(
imageMoved => {
if (imageMoved) {
return RNFS.scanFile(newFilepath);
} else {
return false;
}
}
);
console.log("image moved", imageMoved);
} catch (error) {
console.log(error);
}
};
using RNFS's scanFile method to force the Media Scanner to realize the file exists. This is rough code I'll need to clean up, but it gets the job done.

Ionic 4 - Native camera plugin issues

I have developed an android application using Ionic4. I am facing some issues with Ionic Native Camera plugin. The following is my code. The issues that i am facing is given below. The version if camera plugin i am using is "#ionic-native/camera": "^5.3.0",.
Issues
Gallery is not opening
Captured image is not returning.
Application crashes after taking picture
html
<img [src]="studentImage!==null ? studentImage: 'assets/icon/ic_avatar.png'" class="add-picture" (click)="addImage()">
.ts
public addImage() {
this.genericServices.presentActionSheet(this.openGallery, this.openCamera);
}
private openCamera = () => {
this.studentImage = this.genericServices.selectPicture('camera');
console.log('Captured Image:=>' + this.studentImage);
}
private openGallery() {
this.studentImage = this.genericServices.selectPicture('gallery');
}
service
public async selectPicture(source) {
let base64Image = null;
const cameraOptions: CameraOptions = {
quality: 75,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.PNG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: source === 'camera' ? this.camera.PictureSourceType.CAMERA : this.camera.PictureSourceType.PHOTOLIBRARY,
correctOrientation: true
};
await this.camera.getPicture(cameraOptions).then((imageData) => {
console.log('Returned Image=>' + base64Image);
return base64Image = 'data:image/jpeg;base64,' + imageData;
}).catch(() => {
});
}
Hard to say what your problem is. I would probably write the code slightly different, like this:
async selectImage() {
const actionSheet = await this.actionCtrl.create({
header: "Select Image source",
buttons: [{
text: 'Load from Library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
await actionSheet.present();
}
And then in the takePicture() method decide what destinationType should be, default is FILE_URI (1).
takePicture(sourceType: PictureSourceType) {
var options: CameraOptions = {
quality: 80,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true,
destinationType: 1,
targetWidth: 1240,
targetHeight: 768,
};
this.camera.getPicture(options)
.then((imageData) => {
// do something with the imageData, should be able to bind it to a variable and
// show it in your html file. You might need to fix file path,
// remember to import private win: any = window, and use it like this.
this.imagePreview = this.win.Ionic.WebView.convertFileSrc(imageData);
}).catch((err) => {
console.warn("takePicture Error: " + err);
});
}
This should work fine... i just tested it. But as i said, there could be several things wrong with your setup. Hope it helps in one way or another... otherwise create a fiddle, and i will gladly look at the code for you.

Upload image to server with XMLHttpRequest and FormData in React-Native

I am trying to upload image to server with progress by using the example provided by:
https://gist.github.com/Tamal/9231005f0c62e1a3f23f60dc2f46ae35
I checked some tutorials, the code should works. But the uri in Android show uri
uri: content://media/external/images/media/4985
The URI come from the component
https://github.com/jeanpan/react-native-camera-roll-picker
The URI should be
file://....
So, why the upload code not working.
How can I convert the
content://... to file://.... to make it possible to upload image to server in React-native? or does my assumed is correct?
I am using react-native-image-picker to get image from library. I have written following code in one method name as selectPhoto() to select image from library.
selectedPhoto = () => {
//Open Image Picker
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
};
ImagePicker.showImagePicker(options, (response) => {
//console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
let source = {uri :response.uri};
console.log(source.uri);
this.setState({
profilePhoto: source
});
}
}); }
This will give me uri of selected image and I have set in state variable. then write following code to upload image.
var profiePicture = {
uri: this.state.profilePhoto.uri,
type: 'image/jpg', // or photo.type image/jpg
name: 'testPhotoName',
}
// API to upload image
fetch('http://www.example.com/api/uploadProfilePic/12345', {
method: 'post',
headers:{
'Accept': 'application/json',
'content-type': 'multipart/form-data',
},
body: JSON.stringify({
'profile_pic' : profiePicture
})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
This code is working in one of the my project.

Categories

Resources