how to automatically open the camera - html

To capture the image from mobile using React js code, I am using the following code
<input type="file" accept="image/*" capture onChange={this.loadFile}/>
This input tag is dependent on the state variables in reacting. When the input tag gets rendered, firstly it will ask the user to click the "choose file "button and then will open the camera.
So, can we open the camera directly such that the "Choose File" button doesn't come and directly on changing the state values the camera gets open?
The loadFile handler function is :-
loadFile = (event: any) => {
var reader = new FileReader();
reader.onload = function() {
output: HTMLImageElement;
var output = document.getElementById("output");
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
// console.log(event.target.files[0]);
this.setState({
activeCameraToggle: 0,
photo1: event.target.files[0]
});
};

Check this library:
https://github.com/react-community/react-native-image-picker
After adding it to your project do this:
// Launch Camera:
ImagePicker.launchCamera(options, (response) => {
// Same code as in above section!
});

Related

How to load file after being uploaded (not saved in database yet) in angular, html

I have a file upload control in my angular app where user could upload any type of file except a few ones .exe, .sql etc
<input type="file" id="file" #file (change)="fileUploadHandler($event)" multiple>
fileupload.component.ts
fileUploadHandler(event: Event) {
const inputElement = event.target as HTMLInputElement;
if (inputElement.files && inputElement.files?.length) {
_each(inputElement.files, (_file) => {
const fileSize = _file.size;
if (fileSize < this.MAX_DOC_SIZE) {
const fileName = _file.name?.trim();
const doc = new Document();
doc.name = fileName;
doc.extension = fileName.slice(fileName.lastIndexOf('.') + 1);
doc.size = fileSize;
this.docs.push(doc);
}
});
}}
This list the files in UI as below
Now what I need is that when user click on a file, that file should open in a new tab
how can I do this?
On googling I see suggestions to use FileReader & gave a try
_each(inputElement.files, (_file) => {
const reader = new FileReader();
const data = reader.readAsDataURL(_file);
console.log(data) // nothing is printed on console
Please suggest. Thanks!
You have to enhance the code a little bit (as #mav-raj also stated). In Angular you can use the following:
_each(inputElement.files, (_file) => {
const reader = new FileReader();
reader.onloadend = ((result) => {
console.log(result) // now something will be printed!
});
reader.readAsDataURL(_file);
})

How to process image input to Angular app in an <img> element?

I am trying to create an Angular PWA that is able to take a picture, and after taking it to display it in an img element.
The first step I succeeded in: I now have an FAB button that opens the camera viewfinder (using the html input tag) with this small piece of code:
const element: HTMLElement = document.getElementById('imageCapturer') as HTMLElement;
element.click();
This simulates a click on the following HTML element:
<input type="file" accept="image/*" capture="environment" id="imageCapturer"">
However, after taking a picture I then want to use the image to render it in an img element (and also sending the image to a database with an API call)
I have tried multiple solutions including trying to add the file.name as src to the img element, and trying to create a new img HTML element with an attribute that uses the file. But I am still unable to process the image to be used in the img tag. Can somebody explain to me what the proper way to process the file is to be able to do this?
Cheers!
I solved this problem in the following way:
First, I changed the HTML to this:
<input type="file" accept="image/*" id="imageCapturer" style="display: none;" (change)="useImage($event)">
<img *ngIf="URL" [src]="URL" id="imageViewer">
Then the function useImage looks like this:
useImage(event) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // Read file as data url
reader.onloadend = (e) => { // function call once readAsDataUrl is completed
this.URL = e.target['result']; // Set image in element
this._changeDetection.markForCheck(); // Is called because ChangeDetection is set to onPush
};
}
}
Now whenever a new image is captured or selected it is updated in the view
You can use event change of input file.
This example:
$('#imageCapturer').on('change', function () {
var input = $(this)[0];
if (input.files && input.files[0]) {
var fileName= input.files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
var buffer = e.target.result;
var fileSize = input.files[0].size / 1024 / 1024; // in MB
// SET IMG DISPLAY
$('#image-display').attr('src', buffer).css({
'max-height': '170px',
'max-width': '170px',
};
reader.readAsDataURL(input.files[0]);
}
});
Note: You add more attribute [enctype="multipart/form-data"] in tag form when sumbit form it will send file byte[].
<form id="process_form" method="POST" enctype="multipart/form-data" autocomplete="off" role="form" data-parsley-focus="none">

angular2 filereader mysteriously fails

I'm using the setup shown below to read image file in angular2. I'm using input element to show the window to choose file and then trigger the addThumbnail function when the file is chosen. The click on the input is being triggered by another button. I noticed that the trigger of addThumbnail function sometimes fails silently i.e. the function is not even triggered after choosing a file. This happens may be 1 out of 5 times I'm not sure if this could happen because of the size of the file. I tried to debug this by setting a breakpoint inside addThumbnail function but that is not even being triggered.
<div class="extra-image-container">
<input type="file" accept="image/*" (change)="addThumbnail($event)" style="display:none;" #fileInput2/>
<div class="thumbnail-button" (click)="fileInput2.click()">
<span><i class="material-icons">photo_camera</i></span><br>
<span>Extra Images</span>
</div>
</div>
This is the addThumbnail function and the file reader function I'm using.
addThumbnail(event) {
console.log('adding thumbnail');
var subscription = this.readImage(event.target).subscribe((result) => {
this.thumbnails.push(result.imageUrl);
this.editedThumbnails.push(result.imageUrl);
subscription.unsubscribe()
});
}
readImage(inputValue: any) : Observable<any> {
var file:File = inputValue.files[0];
var myReader:FileReader = new FileReader();
var observable = new Observable(observer => {
myReader.onloadend = (e) => {
observer.next({imageUrl: myReader.result});
console.log("image loaded");
// var image = new Image();
// image.addEventListener("load", () => {
// observer.next({
// imageWidth: image.width,
// imageHeight: image.height,
// imageSize: file.size/1000,
// imageUrl: myReader.result
// })
// console.log("image loaded");
// })
// image.src = myReader.result;
}
myReader.readAsDataURL(file);//triggers the callback
})
return observable
}
It turns out that if you read same file one after another, then the change is not triggered because the files are same. So, to fix this all I had to do was set the value of input element to empty string after a file is loaded.
#ViewChild('fileInput2') private thumbImageInput: ElementRef;
// and in the addThumbnail method:
addThumbnail(event) {
var subscription = this.readImage2(event.target).subscribe((result) => {
this.thumbnails.push(result.imageUrl);
this.editedThumbnails.push(result.imageUrl);
window.URL.revokeObjectURL(result.imageUrl);
this.thumbImageInput.nativeElement.value = '';
});
}

Determine file type using Electron dialog

I used HTML5 File API to drag a file into an Electron application and obtained file details (name, mime-type, size, etc.). How can I achieve the same when selecting a file via Electron's dialog module? Below is the code (renderer process) that leverages HTML5's File API:
const {dialog} = require('electron').remote;
// Using jQuery ($)
var holder = $('#holder');
holder.on('drag dragstart dragend dragover dragenter dragleave drop', function(evt) {
evt.preventDefault();
evt.stopPropagation();
})
.on('drop', function(evt) {
let file = evt.originalEvent.dataTransfer.files[0];
console.log(file.name);
console.log(file.type);
console.log(file.size);
})
.on('click', function(evt) {
dialog.showOpenDialog({
properties: [ 'openFile' ]
}, function(file) {
console.log(file); // just displays local, full path
// code to get name, type, size... how do I?
});
});
Check this library: mmmagic, it will do just what you want.

chrome.storage.sync does not store the data

I am trying to store the data a user enters inside a textarea in a popup.html. Using jQuery on window unload the data should be synced and on window ready the data should be restored. However, when opening popup.html the content of the textarea is undefined. This is the jQuery code which I am loading in popup.html:
$(window).unload (
function save() {
var textarea = document.querySelector("#contacts").value;
// Old method of storing data locally
//localStorage["contacts"] = textarea.value;
// Save data using the Chrome extension storage API.
chrome.storage.sync.set({contacts: textarea}, function() {
console.log("Contacts saved");
});
});
$(window).ready(
function restore() {
var textarea = document.querySelector("#contacts");
// Old method of retrieving data locally
// var content = localStorage["contacts"];
chrome.storage.sync.get('contacts', function(r) {
console.log("Contacts retrieved");
var content = r["contacts"];
textarea.value = content;
});
});
From popup.js you can invoke a method in background.js file to save the data:
popup.js:
addEventListener("unload", function(){
var background = chrome.extension.getBackgroundPage();
background.mySavefunction(data);
}
background.js:
function mySaveFunction(data){
chrome.storage.sync.set(data, function(){
console.log("Data saved.");
});
}
I found a solution. Instead of using $(window).unload() I now use a submit button which needs to be clicked before closing popup.html:
$("#save-button").click(function() {
var textarea = document.querySelector("#contacts").value;
var save = {};
save["contacts"] = textarea;
// Save data using the Chrome extension storage API.
chrome.storage.sync.set(save, function() {
console.log("Contacts saved");
});
$("#confirm").text("Contacts saved.").show().fadeOut(5000);
});