android java take a picture and upload
Capturing an Image from the User
— Updated
Many browsers now have the ability to access video and sound input from the user. However, depending on the browser it might be a full dynamic and inline feel, or it could be delegated to another app on the user'southward device. On top of that, not every device even has a camera. So how can you create an experience that uses a user generated image that works well everywhere?
Start simple and progressively #
If you desire to progressively enhance your feel, y'all need to outset with something that works everywhere. The easiest thing to practise is simply ask the user for a pre-recorded file.
Ask for a URL #
This is the best supported just to the lowest degree satisfying option. Get the user to give you a URL, and so apply that. For merely displaying the image this works everywhere. Create an img
element, set the src
and y'all're done.
Though, if you lot desire to manipulate the image in any manner, things are a scrap more than complicated. CORS prevents you from accessing the actual pixels unless the server sets the advisable headers and you mark the image equally crossorigin ; the only practical fashion around that is to run a proxy server.
File input #
You can likewise use a unproblematic file input element, including an accept
filter that indicates you only want paradigm files.
<input blazon = "file" accept = "epitome/*" />
This method works on all platforms. On desktop information technology will prompt the user to upload an image file from the file organisation. In Chrome and Safari on iOS and Android this method will give the user a option of which app to use to capture the image, including the option of taking a photo directly with the camera or choosing an existing prototype file.
The data can then be attached to a <grade>
or manipulated with JavaScript by listening for an onchange
event on the input element and then reading the files
property of the event target
.
<input type = "file" accept = "image/*" id = "file-input" />
<script >
const fileInput = document. getElementById ( 'file-input' ) ; fileInput. addEventListener ( 'change' , ( e ) =>
doSomethingWithFiles (eastward.target.files) ,
) ;
</script >
The files
belongings is a FileList
object, which I'll talk more than near later on.
Yous tin too optionally add the capture
aspect to the element, which indicates to the browser that you prefer getting an image from the camera.
<input blazon = "file" accept = "image/*" capture />
<input blazon = "file" accept = "image/*" capture = "user" />
<input type = "file" accept = "image/*" capture = "surround" />
Adding the capture
attribute without a value let'due south the browser make up one's mind which camera to use, while the "user"
and "environs"
values tell the browser to prefer the front and rear cameras, respectively.
The capture
attribute works on Android and iOS, but is ignored on desktop. Be aware, even so, that on Android this ways that the user will no longer take the option of choosing an existing movie. The system camera app will exist started directly, instead.
Drag and drop #
If you are already adding the power to upload a file, at that place are a couple of easy ways that y'all can brand the user experience a little richer.
The first is to add a drop target to your page that allows the user to drag in a file from the desktop or some other application.
<div id = "target" > You tin can elevate an image file here </div >
<script >
const target = document. getElementById ( 'target' ) ; target. addEventListener ( 'drop' , ( eastward ) => {
e. stopPropagation ( ) ;
e. preventDefault ( ) ;
doSomethingWithFiles (e.dataTransfer.files) ;
} ) ;
target. addEventListener ( 'dragover' , ( e ) => {
east. stopPropagation ( ) ;
e. preventDefault ( ) ;
e.dataTransfer.dropEffect = 'copy' ;
} ) ;
</script >
Similar to the file input, you lot can get a FileList
object from the dataTransfer.files
belongings of the driblet
event;
The dragover
event handler let's you point to the user what will happen when they drib the file past using the dropEffect
property.
Drag and drop has been effectually for a long fourth dimension and is well supported by the major browsers.
Paste from clipboard #
The final style to go an existing image file is from the clipboard. The code for this is very simple, but the user experience is a little harder to get right.
<textarea id = "target" > Paste an image here </textarea >
<script >
const target = certificate. getElementById ( 'target' ) ; target. addEventListener ( 'paste' , ( east ) => {
e. preventDefault ( ) ;
doSomethingWithFiles (e.clipboardData.files) ;
} ) ;
</script >
(e.clipboardData.files
is notwithstanding some other FileList
object.)
The catchy part with the clipboard API is that, for full cross-browser back up, the target chemical element needs to exist both selectable and editable. Both <textarea>
and <input type="text">
fit the bill hither, as practice elements with the contenteditable
attribute. But these are also plainly designed for editing text.
It tin can be difficult to brand this work smoothly if you don't desire the user to be able to input text. Tricks like having a hidden input that gets selected when yous click on some other element may make maintaining accessibility harder.
Handling a FileList object #
Since virtually of the above methods produce a FileList
, I should talk a trivial nigh what that is.
A FileList
is similar to an Array
. Information technology has numeric keys and a length
holding, but it isn't actually an array. There are no array methods, like forEach()
or pop()
, and it isn't iterable. Of course, you can get a real Array by using Array.from(fileList)
.
The entries of the FileList
are File
objects. These are exactly the same equally Hulk
objects except that they accept boosted name
and lastModified
read-but properties.
<img id = "output" />
<script >
const output = certificate. getElementById ( 'output' ) ; function doSomethingWithFiles ( fileList ) {
let file = null ;
for ( let i = 0 ; i < fileList.length; i++ ) {
if (fileList[i] .type. lucifer ( / ^paradigm\/ / ) ) {
file = fileList[i] ;
break ;
}
}
if (file !== naught ) {
output.src = URL . createObjectURL (file) ;
}
}
</script >
This example finds the offset file that has an image MIME type, only it could as well handle multiple images being selected/pasted/dropped at once.
Once y'all have access to the file you can do anything you want with it. For example, you lot can:
- Draw information technology into a
<sheet>
element and so that you lot tin can manipulate it - Download it to the user'south device
- Upload it to a server with
fetch()
Access the camera interactively #
Now that you've covered your bases, it'due south fourth dimension to progressively heighten!
Mod browsers tin get straight access to cameras, allowing you to build experiences that are fully integrated with the web page, so the user demand never go out the browser.
Acquire access to the camera #
You can direct access a camera and microphone by using an API in the WebRTC specification called getUserMedia()
. This will prompt the user for access to their connected microphones and cameras.
Support for getUserMedia()
is pretty good, but it isn't nevertheless everywhere. In item, information technology is not available in Safari ten or lower, which at the time of writing is still the latest stable version. Notwithstanding, Apple have announced that it will be available in Safari 11.
It's very simple to notice support, even so.
const supported = 'mediaDevices' in navigator;
When y'all phone call getUserMedia()
, you need to laissez passer in an object that describes what kind of media you desire. These choices are called constraints. There are a several possible constraints, covering things like whether yous adopt a front- or rear-facing photographic camera, whether y'all want audio, and your preferred resolution for the stream.
To get data from the photographic camera, nonetheless, you need but ane constraint, and that is video: true
.
If successful the API volition return a MediaStream
that contains data from the camera, and you can then either attach it to a <video>
element and play it to show a existent time preview, or attach information technology to a <canvas>
to go a snapshot.
<video id = "actor" controls autoplay > </video >
<script >
const player = certificate. getElementById ( 'thespian' ) ; const constraints = {
video : true ,
} ;
navigator.mediaDevices. getUserMedia (constraints) . and then ( ( stream ) => {
thespian.srcObject = stream;
} ) ;
</script >
By itself, this isn't that useful. All you can do is take the video data and play it dorsum. If you desire to get an paradigm, you take to exercise a petty actress work.
Take hold of a snapshot #
Your all-time supported choice for getting an image is to depict a frame from the video to a sail.
Dissimilar the Web Sound API, there isn't a dedicated stream processing API for video on the web and then you have to resort to a tiny bit of hackery to capture a snapshot from the user's camera.
The process is as follows:
- Create a sail object that volition hold the frame from the photographic camera
- Get access to the camera stream
- Attach information technology to a video element
- When you want to capture a precise frame, add together the data from the video element to a canvas object using
drawImage()
.
<video id = "role player" controls autoplay > </video >
<button id = "capture" > Capture </push button >
<sheet id = "canvas" width = "320" superlative = "240" > </sail >
<script >
const thespian = document. getElementById ( 'histrion' ) ;
const canvass = document. getElementById ( 'canvas' ) ;
const context = canvas. getContext ( '2d' ) ;
const captureButton = certificate. getElementById ( 'capture' ) ; const constraints = {
video : true ,
} ;
captureButton. addEventListener ( 'click' , ( ) => {
// Draw the video frame to the canvass.
context. drawImage (role player, 0 , 0 , sail.width, canvass.height) ;
} ) ;
// Attach the video stream to the video element and autoplay.
navigator.mediaDevices. getUserMedia (constraints) . then ( ( stream ) => {
player.srcObject = stream;
} ) ;
</script >
One time you have information from the photographic camera stored in the canvas you lot can practice many things with it. You could:
- Upload information technology direct to the server
- Store it locally
- Apply funky effects to the prototype
Tips #
Finish streaming from the camera when not needed #
Information technology is practiced practice to cease using the camera when y'all no longer need information technology. Non only will this save bombardment and processing ability, it will also give users confidence in your application.
To end access to the camera you lot tin simply call stop()
on each video track for the stream returned by getUserMedia()
.
<video id = "role player" controls autoplay > </video >
<button id = "capture" > Capture </push button >
<canvas id = "sheet" width = "320" height = "240" > </canvas >
<script >
const thespian = document. getElementById ( 'player' ) ;
const canvas = certificate. getElementById ( 'canvas' ) ;
const context = canvas. getContext ( '2d' ) ;
const captureButton = certificate. getElementById ( 'capture' ) ; const constraints = {
video : true ,
} ;
captureButton. addEventListener ( 'click' , ( ) => {
context. drawImage (player, 0 , 0 , canvas.width, sheet.height) ;
<strong>
// Stop all video streams. player.srcObject.getVideoTracks().forEach(track
=> track. stop ( ) ) ;
< /stiff> ;
} ) ;
navigator.mediaDevices. getUserMedia (constraints) . and then ( ( stream ) => {
// Adhere the video stream to the video element and autoplay.
actor.srcObject = stream;
} ) ;
</script >
Inquire permission to use camera responsibly #
If the user has not previously granted your site access to the photographic camera then the instant that you call getUserMedia()
the browser will prompt the user to grant your site permission to the camera.
Users hate getting prompted for access to powerful devices on their machine and they volition frequently block the asking, or they volition ignore it if they don't understand the context for which the prompt has been created. It is best practice to only ask to access the camera when first needed. One time the user has granted access they won't be asked over again. Notwithstanding, if the user rejects admission, you tin can't go access again, unless they manually change camera permission settings.
Compatibility #
More information most mobile and desktop browser implementation:
- srcObject
- navigator.mediaDevices.getUserMedia()
We likewise recommend using the adapter.js shim to protect apps from WebRTC spec changes and prefix differences.
Feedback #
Concluding updated: — Improve commodity
Source: https://web.dev/media-capturing-images/
0 Response to "android java take a picture and upload"
Post a Comment