Is there by any chance a way of letting the user select an image from his hard drive and without submitting it to the server use this image in the browser?
I need this because I want the users to be able to crop an image before sending this cropped image to the server (thus saving a post and some bytes of data).
What I tried to do is using an input type file and then capturing the submit event, but the value from the input is just a fake path (useless).
Any help would be greatly appreciated.
Here is a very basic example (with many globals, without input validation...) of image scaling: http://jsfiddle.net/89HPM/3/ . It's using the File API and a canvas element.
As #anu said the save can be done using toDataUrl method of the canvas.
In similar way you can achieve crop.
JavaScript
(function init() {
document.getElementById('picture').addEventListener('change', handleFileSelect, false);
document.getElementById('width').addEventListener('change', function () {
document.getElementById('canvas').width = this.value;
renderImage();
}, false);
document.getElementById('height').addEventListener('change', function () {
document.getElementById('canvas').height = this.value;
renderImage();
}, false);
}());
var currentImage;
function handleFileSelect(evt) {
var file = evt.target.files[0];
if (!file.type.match('image.*')) {
alert('Unknown format');
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
currentImage = e.target.result;
renderImage();
};
})(file);
reader.readAsDataURL(file);
}
function renderImage() {
var data = currentImage,
img = document.createElement('img');
img.src = data;
img.onload = function () {
var can = document.getElementById('canvas'),
ctx = can.getContext('2d');
ctx.drawImage(this, 0, 0, can.width, can.height);
};
}
HTML
<input type="file" name="picture" id="picture" /><br />
<input type="text" id="width" value="200" />
<input type="text" id="height" value="200" /><br />
<canvas width="200" height="200" style="border: 1px solid black;" id="canvas"></canvas>
Here is a blog post which I made about that basic example: blog.mgechev.com
New HTML5 File API is probably the closest solution to what your looking for:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
It allows you to browse for and read files within Javascript. Do whatever processing you like, and then upload to the server. Anything besides this is going to be very tricky indeed, and probably an unavoidable trip to the server and back.
Downside here is browser support.....as always
I am not sure which browsers work perfectly but HTML5 got DnD and File API. Let me give you steps which can work for you using FileAPI.
DnD API: Starts with the drop event when the user releases the mouse and the mouse-up event occurs.
DnD API: Get the DataTransfer object from the drop event
File API: Call DataTransfer.files to get a FileList, representing the list of files that were dropped.
File API: Iterate over all the individual File instances and use a FileReader object to read their content.
File API: Using the FileReader.readAsDataURL(file) call, every time a file is completely read, a new “data URL” (RFC 2397) formatted object is created and an event wrapping it is fired to the onload handler on the FileReader object.
FYI: The “data URL” object is Base64-encoded binary data, with a spec-defined header sequence of chars. Browsers understand them.
HTML5 DOM: set the image href to the File Data URL
You can't, for the following reasons:
For the reasons stated in this post: Full path from file input using jQuery
The fact that if you even try to create an img element loading a
local file path you'll get the error Not allowed to load local
resource: in your browser's console.
The fact that once you have an image in place you can only alter it's
appearance on screen and not alter the file on the system or send the altered image up to the server
You've stated that you need cross browser support, so HTML5 File API and Canvas API are out, even though they would only allow part of the functionality anyway.
I've just solved a problem closed to yours.
As everybody said you can't got the real image file address. But, you can create a temporary path and show the image in your page without submiting it to server. I'll show how easy it is, next to next paragraph.
Once you show it you can use some javascripts events to "pseudo-crop-it" and get the crop params (corners). Finaly you can add the params to some hidden field and submit the form. As a result you may use som php to crop the submited image at server and to save the result using a number of image formats as .png, jpg, gif, etc. Sorry if i do not write a complete solution, have not enough time.
/* some scripting to bind a change event and to send the selected image
to img element */
$(document.ready(function(){
$("input:file").each(function(){
var id = '' + $(this).attr('id');
var idselector = '#'+id, imgselector=idselector+'-vwr';
$(idselector).bind("change", function( event ){
(imgselector).fadeIn("fast").attr('src',
URL.createObjectURL(event.target.files[0]));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!-- create a img element to show the selected image and an input file element to select the image.
ID attribute is the key to have an easy and short scripting
note they are related suffix -vwr makes the difference
-->
<img src="" id="image-input-vwr" alt="image to be cropped">
<input type="file" id="image-input" name="image_input">
Hope it help some body as it is a very old question.
Luis G. Quevedo
Related
I have an input field, where users can choose what image they want to upload, and then I need to send to cloud storage. The problem is, I don't know how to get the file they selected. I saw a lot questions like this, this, this, etc. Most of the questions I saw, like this one, are asking for previewing the images BEFORE uploading. I don't think I need to preview the image, i just want to upload it. How do I do this? Here is my current code:
function addImage() {
$("#addImage").append('\
<input type="file" id="image" accept="image/*">\
<button type="submit">ok</button>\
<button onclick="cancelAddImage()">cancel</button>');
$("#addImage").submit(function() {
var image = $("#image").files;
console.log(image);
storage.ref("images").put(image).then(function(snapshot) {
console.log('Uploaded a file!');
});
});
}
The console.log() for this is giving "undefined". I also tried .files[0] instead of .files;, and many others.
In your html code, you place the input field with a an id. For example, if you want to upload a picture from the camera:
<input type="file" accept="image/*" capture="camera" id="cameraInput">
Then in your js code, you will listen to change events on this element :
let storageRef = firebase.storage().ref('photos/myPictureName')
let fileUpload = document.getElementById("cameraInput")
fileUpload.addEventListener('change', function(evt) {
let firstFile = evt.target.files[0] // upload the first file only
let uploadTask = storageRef.put(firstFile)
})
Of course you need to have somehow included the firebase js library before.
And if you write in an older version of js, you also need to replace the let with var and add ; at the end of your lines.
I have done the following code to convert HTML Content(DIV) to save as Image (JPEG, PNG,GIF Etc) with below code.
<pre>
html2canvas($(".mainbox"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsImage(canvas);
$("#FinalImage").append(canvas);
}
});
</pre>
I have also included html2canvas.js,base64.js and canvas2image.js in my page. At the end Image is shown in #FinalImage DIV and browser ask me to save it in my drive up to now all are working fine.
Now the question is name of the saved image has no Extension, every time I need to go to the image and assign the Extension(".jpg",".png" etc...). Is there any solution to set extension by default when user saves from the browser.
Thanks in advance.
I have done same functionality for capturing signature. This is different from your approach. but this code snippet may help you. plz comment if u need whole source code.
var canvas = document.getElementById(<canvas element id>)// get canvas element
var dataURL = canvas.toDataURL("image/png");// convert to img, specify extension
document.getElementById(<new image id>).src = dataURL; // write as an image
In line two I specified png.there you can change the extension of image. Hope it helps
Refresh Image Src content and Stop the refreshing
Hi, i have a function that refresh the "src" attr every second. , now i want when i click button stop, it will stop the interval, in addtion, to make a button to take the picture and save it to computer, like snapshot.
<img src="http://someurl" id="image1" class="g" />
<button id="stop">STOP!</button>
<button id="capture">capture</button>
Example
you can see here what i wrote and give me directions , thanks.
Canvas2Image plugin might help you.
Using the HTML5 canvas element, you can create all sorts of cool graphics client-side on the fly using Javascript. However, the canvas image cannot (in all browsers) simply be saved to disk as any other image.
Luckily there is a neat function on the the canvas object called toDataURL(). This functions encodes the image data as a base64 encoded PNG file and returns it as a data: URI.
To work in IE you'll need a canvas support library such as http://excanvas.sourceforge.net/
Also check out this question.
Edit:
Refreshing image is simple:
//Declare array of images
var images = ['http://www.creativereview.co.uk/images/uploads/2012/10/1_press_image_l_for_the_lol_of_cats_l_maru_0.jpg',
'http://blog.naseeb.com/wp-content/uploads/2010/12/cute-cat.jpg',
'http://www.helpinghomelesscats.com/images/cat1.jpg'];
var loop = 0;
//This function will refresh image on specified interval
function refreshImages() {
$('#myimage').attr('src', images[loop]);
loop++;
if (loop === images.length) {
loop = 0;
}
}
//Set Refresh time here
var setInt = self.setInterval(function() {
refreshImages();
}, 1000);
//This button stops the image refreshing
$('#stop').click(function() {
setInt = window.clearInterval(setInt);
});
//Add image capture code here
Working DEMO
Recently I've been looking into adding a simple HTML5 drag and drop to my already simple php file upload script.
I have read lots of tutorials and other solutions but I can't seem to understand the whole sending the file to server part.
From what I understand, XMLHttpRequest will send the data, but it will do it without reloading the page. This, I do not want. Currently the script I'm using will take the POST data and produce the file upload output, eg. server download link, thumbnail if image etc.
How can I have the drag and drop submit the POST data and either access the upload output or reload the page?
Edit:
I'm using the following for the drag and drop:
<div id="drop_zone">Drag and drop a file here</div>
<script>
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
uploadFile(files[0]); //<-- This is where most examples will use XMLHttpRequest to construct form and send data
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
document.getElementById('drop_zone').style.backgroundColor = "#faffa3";
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
function handleDragLeave(evt) {
document.getElementById('drop_zone').style.backgroundColor = "";
}
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
dropZone.addEventListener('dragleave', handleDragLeave, false);
</script>
If you use JQuery or some other event-capable javascript library you should be able to catch the drag event and submit your form.
http://docs.jquery.com/UI/API/1.8/Draggable
http://api.jquery.com/on/
But no XMLHttpRequest involved...
After more reading and searching around I've come to the conclusion that what I originally wanted cannot be done.
The solution I am going with is to simply have a large transparent/hidden <input type="file"> covering the drop zone. The dropped filename will be read from the input with javascript and displayed in the drop zone. This of course will rely on the browser to support the drag and drop files into html file inputs.
From there my upload script will pretty much operate as if the user had used the visible file selector.
Apologies for not being too clear on what I wanted. I wasn't so sure myself. And thanks for the replies/comments.
To be more specific, I want to use a form with one or more file input fields used for images. When those fields are changed, I'd like to show a preview of the associated image, before sending the data to the server.
I've tried a number of javascript approaches, but I always run into security errors.
I wouldn't mind using java or flash, as long as the solution degraded gracefully for those users who didn't have them. (They wouldn't get previews, and they wouldn't get an annoying 'install this thing' either.)
Has anyone done this in a simple, reusable way?
P.S. I know there's a sandbox, but does the sandbox have to be in a dark, locked room with all the windows blacked out?
No need for fancy stuff. All you need is the createObjectURL function, which creates a URL that can be used as the image src, and can come straight from a local file.
Let's say you selected a couple of images from the user's computer using a file input element (<input type="file" />). Here's how you would create previews for image files for it:
function createObjectURL(object) {
return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
function revokeObjectURL(url) {
return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}
function myUploadOnChangeFunction() {
if(this.files.length) {
for(var i in this.files) {
var src = createObjectURL(this.files[i]);
var image = new Image();
image.src = src;
// Do whatever you want with your image, it's just like any other image
// but it displays directly from the user machine, not the server!
}
}
}
The first step is finding out the image path. JavaScript is allowed to interrogate the upload control for a filename/path, but (for reasons of security) various browsers show different things to the JS engine than they display to the user - they tend to keep the filename intact so you can at least validate its extension, but you may get c:\fake_path\ or some similarly obfuscated thing prepended to the filename. Trying this on various browsers will give you an idea as to what gets returned as a real path, and what gets faked out, and where.
The second step is displaying the image. It's possible to display local images if you know their paths, via img tags with file:// source URLs, if the user's browser allows the file:// scheme. (Firefox doesn't, by default.) So if you can get the user to tell you what the full path to the image is, you can at least try to load it.
JavaScript has no access to the local file system for security purposes, period.
Here's a jQuery + PHP script for uploading an image an previewing it.
I have only ever seen Java applets that do this, for example, the image uploading applet on Facebook. The downside to the Java approach is that the user will be prompted to trust the applet before it runs, which is a kind of annoyance, but this allows the applet to present a file browser with image previews or do more interesting things like allows the user to upload an entire directory.
You can try this approach, although it seems it doesn't work on IE.
http://saravani.wordpress.com/2012/03/14/preview-of-an-image-before-it-is-uploaded/
It's simple and fast to code.
I put the code here just in case the source dies:
Script:
<!-- Assume jQuery is loaded -->
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
In the HTML:
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="img_prev" src="#" alt="your image" />
</body>