I use an input field on a website so that a user can take himself into photo.
On iPad, iPhone, the resulting picture is upside down. How can I easily detect if the user used the camera so that I rotate the image via Javascript ?
I use the picture in a Javascript Canvas after.
I got this input field :
<div class="input-field">
<label>Choose image or take a picture :</label>
>input type="file" id="imageLoader" name="imageLoader" accept="image/*"/>
</div>
And in JS :
var imageLoader;
imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', _handleImage, false);
function _handleImage( e ){
var reader = new FileReader();
reader.onload = function(event){
picture.onload = function(){
// The image here is upside down :( I want to turn it to 180 degrees here
do_stuff( );
};
picture.src = event.target.result;
};
reader.readAsDataURL(e.target.files[0]);
}
I managed to do it using those libs ( I don't have the links in my mind but search google, those specific versions just works ):
Javascript EXIF Reader 0.1.4
Binary Ajax 0.1.10
Heres the full code :
HTML :
<div class="input-field">
<label>Choose image or take a picture :</label>
<input type="file" id="imageLoader" name="imageLoader" accept="image/*"/>
</div>
JS :
var imageLoader, _isUpsideDown = false;
imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', _handleImage, false);
function _handleImage( e ){
var reader = new FileReader();
reader.onload = function(event){
picture.onload = function(){
// Launch Canvas, display image, etc...
doStuff();
};
picture.src = event.target.result;
};
reader.readAsDataURL(e.target.files[0]);
// Second file reader which will read the file as binaryString to detect the orientation.
var file = this.files[0]; // file
filereaderString = new FileReader; // to read file contents
filereaderString.onloadend = function() {
// get EXIF data
var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
// the 3 value means that the image is upside down. 1 is when the image is correct size.
if( exif.Orientation === 3 ){
_isUpsideDown = true;
}
};
filereaderString.readAsBinaryString(file); // read the file
}
From which camera? front or rear? Because they are different too and depends what you want from them. I considered the rear camera.
I created some buttons representing what you have to do for each case:
var angle = 0;
$('#portraitButton').on('click', function() {
angle = 90;
$("#picture").rotate(angle);
});
$('#landscapeLeft').on('click', function() {
angle = 180;
$("#picture").rotate(angle);
});
$('#landscapeRight').on('click', function() {
angle = 180;
$("#picture").rotate(angle);
});
$('#upsideDown').on('click', function() {
angle = -90;
$("#picture").rotate(angle);
});
The demo is here: http://jsfiddle.net/s6zSn/382/
I hope i could help :)
Related
I am using the awesome jquery-cropper plugin from fengyuanchen.
I'm having the issue of when certain images get uploaded it rotates and it is not on the right side which I have to make the user rotate them. I will upload the image via ajax. I'm getting the error rotate is not defined which I have been stuck a couple of hours.
$('#profilePhoto').on( 'change', function(){
if (this.files && this.files[0]) {
if ( this.files[0].type.match(/^image\//) ) {
var reader = new FileReader();
reader.onload = function(evt) {
var img = new Image();
img.onload = function() {
$("#profileImageContainer").hide();
$("#rotateImg").show();
context.canvas.height = img.height;
context.canvas.width = img.width;
context.drawImage(img, 0, 0);
cropper = canvas.cropper({
aspectRatio: 1 / 1,
rotatable: true,
});
$('#btnCrop').click(function() {
// Get a string base 64 data url
var croppedImageDataURL = canvas.cropper('getCroppedCanvas').toDataURL("image/png");
});
$('#rotateImg').click(function () {
cropper.cropper.rotate(90);
});
};
img.src = evt.target.result;
};
reader.readAsDataURL(this.files[0]);
}
else {
alert("Invalid file type! Please select an image file.");
}
}
else {
alert('No file(s) selected.');
}
});
The main problem here is about scopes since it looks like it is not reconizing the cropper variable.
This problems surfaces because when the user upload a photo sometimes this photo rotate automatically. If I could solve this problem first without having to make the user rotate the image would be better
Really stupid mistake. Instead of:
cropper.cropper().rotate(90);
I should apply:
cropper.cropper('rotate', 90);
I am starting with this working JavaScript code:
// Begin File Open Code.
function fileOpen()
{
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('iDisplay');
fileInput.addEventListener('change', function(e)
{
file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType))
{
var reader = new FileReader();
reader.onload = function(e)
{
iDisplay.innerHTML = "";
image = new Image();
image.src = reader.result;
image.id = "I"; // Add an id attribute so the image editor code can access the image.
iDisplay.appendChild(image);
image.onload = function()
{
c = document.getElementById("canvas1");
context = c.getContext("2d");
c.width = image.width;
c.height = image.height;
context.drawImage(image,0,0);
}
}
reader.readAsDataURL(file);
moreFiles++;
document.getElementById("fileInput").disabled = true;
document.getElementById("fileInputD").innerHTML = '<p>Please refresh page to open a new image</p>';
}
else
{
iDisplay.innerHTML = "File type not supported."
}
});
}
// End File Open Code
And trying to break it up into two separate functions, fileOpen() and loadImage(). The reason is that loadImage will also be used to load default images. I came up with several non-working versions. After reading about the topic here, most recently this answer Javascript FileReader onload not firing I adjusted the code as follows:
// Begin File Open Code
function fileOpen(radio)
{
fileInput = document.getElementById('fileInput');
fileDisplayArea = document.getElementById('iDisplay');
fileInput.addEventListener('change', function(e)
{
file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType))
{
reader = new FileReader();
reader.onload = fileSelected;
function fileSelected(e)
{
iDisplay.innerHTML = "";
image = new Image();
image.src = reader.result;
image.id = "I"; // Add an id attribute so the image editor code can access the image.
iDisplay.appendChild(image);
image.onload = loadImage();
}
}
else
{
iDisplay.innerHTML = "File type not supported."
}
})
}
// End File Open Code
// Begin Load Image Code - This will be used to load a preselected image
function loadImage()
{
c = document.getElementById("canvas1");
context = c.getContext("2d");
c.width = image.width;
c.height = image.height;
context.drawImage(image,0,0);
reader.readAsDataURL(file);
document.getElementById("fileInput").disabled = true;
document.getElementById("fileInputD").innerHTML = '<p>Please refresh page to open a new image</p>';
}
// End Load Image Code
But, after reviewing in the Chrome Inspector, the code never gets past
reader.onload = fileSelected;
After that line, the function exits, and nothing is loaded. I have spent hours on variations of this code and cannot get it to fire past that line. So, my question is "why?" I should note that I want to stay with pure JavaScript.
Thank you in advance.
There appears to be a bug in Chrome 73 where it isn't fired if you have a debugger statement.
I literally have
reader.readAsText(blob);
debugger;
and it never hits the onload
If I change it to
debugger;
reader.readAsText(blob);
then it works.
Fixed by Chrome 75.
You can also use FileReader.readAsDataURL() to parse the file from your . This will create a string in memory containing a base64 representation of the image.
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
Ref: Preview an image before it is uploaded
Are there any Fabric.JS Wizards out there?
I've done my fair research and I can't seem to find much of an explanation on how to add an image to the fabric.JS canvas.
User Journey:
a) User uploads an image from an input file type button.
b) As soon as they have selected an image from their computer I want to place it into the users canvas.
So far I've got to storing the image into an expression, this is my code below:
scope.setFile = function(element) {
scope.currentFile = element.files[0];
var reader = new FileReader();
/**
*
*/
reader.onload = function(event) {
// This stores the image to scope
scope.imageSource = event.target.result;
scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
};
My HTML/Angular:
<label class="app-file-input button">
<i class="icon-enter"></i>
<input type="file"
id="trigger"
onchange="angular.element(this).scope().setFile(this)"
accept="image/*">
</label>
If you haven't guessed yet I am using a MEAN stack. Mongoose, Express, Angular and Node.
The scope imageSource is what the image is store in. I've read this SO
and it talks about pushing the image to the Image object with my result, and then pass it to the fabric.Image object. Has anyone done a similar thing that they can help me with?
Thanks in advance
**** UPDATE ****
Directive defines the canvas variable:
var canvas = new fabric.Canvas(attrs.id, {
isDrawingMode: true
});
Upload image from computer with Fabric js.
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
canvas{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450"></canvas>
once you have a dataURL done, you can do either:
reader.onload = function(event) {
// This stores the image to scope
fabric.Image.fromURL(event.target.result, function(img) {
canvas.add(img);
});
scope.$apply();
};
Or you put on your image tag an onload event where you do:
var img = new fabric.Image(your_img_element);
canvas.add(img);
This is for drag and drop from desktop using the dataTransfer interface.
canvas.on('drop', function(event) {
// prevent the file to open in new tab
event.e.stopPropagation();
event.e.stopImmediatePropagation();
event.e.preventDefault();
// Use DataTransfer interface to access the file(s)
if(event.e.dataTransfer.files.length > 0){
var files = event.e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (f.type.match('image.*')) {
// Read the File objects in this FileList.
var reader = new FileReader();
// listener for the onload event
reader.onload = function(evt) {
// put image on canvas
fabric.Image.fromURL(evt.target.result, function(obj) {
obj.scaleToHeight(canvas.height);
obj.set('strokeWidth',0);
canvas.add(obj);
});
};
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
}
});
Resources
https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop
Allright, this is going to be quite hard to explain but I will try to explain my problem as clear as possible.
I currently have a HTML5 Canvas with a couple of preloaded shapes which I changed to images. I am using a modified version of this example. On the canvas I have now I can drag, drop and select the shapes which are preloaded.
I have implemented an option to upload a new image to the canvas using this:
var imageLoader = document.getElementById('uploader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var imgNew = new Image();
imgNew.onload = function(){
ctx.drawImage(imgNew, 0, 0);
}
imgNew.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
This will now just put an image in the top-left corner of the canvas and when I select another shape this image will disappear. All shapes that are already in the canvas are in an array called 'shapes'. In the example there is an option to add a new shape when you dubbelclick on the canvas, this is the code:
// double click for making new shapes
canvas.addEventListener('dblclick', function(e) {
var mouse = myState.getMouse(e);
myState.addShape(new Shape(mouse.x - 10, mouse.y - 10, 20, 20, 'rgba(0,255,0,.6)'));
}, true);
This is the addShape part which is called when double clicking:
CanvasState.prototype.addShape = function(shape) {
this.shapes.push(shape);
this.valid = false;
}
What I am trying to do is when I upload an image using the file upload the image should be added to the 'shapes' array so I can also drag,drop and select the uploaded image. (basically I need to do the same with the uploaded image as I can do with the preloaded ones) My guess is that it should be done something like the doubleclick method and addShape but I can't get this to work.
A working version of my current version can be found here:
http://codepen.io/anon/pen/qLuCy/
If anyone knows how I can get this to work it would be great!
first the result, here : http://codepen.io/anon/pen/qBmnC/
Your shape object can only draw one single hard-coded image, so change this and have shape be either a color or an image. In fact for this you just have to change shape.draw since the 'type' of the fill does not matter in the constructor.
So just test the fill and draw accordingly :
// Tekent de Shape
Shape.prototype.draw = function(ctx) {
var locx = this.x;
var locy = this.y;
var fill = this.fill ;
if (typeof fill == 'string' )
{
ctx.fillStyle = fill;
ctx.fillRect(locx, locy, this.w, this.h);
}
else
{
ctx.drawImage(fill, locx, locy, this.w, this.h);
}
}
then on image load i just add a shape that has this image as fill :
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var imgNew = new Image();
imgNew.onload = function(){
s.addShape(new Shape(60,60,imgNew.width,imgNew.height,imgNew));
}
imgNew.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
I had to put the shape collection, s, as a global var.
You can also see that i used the same scheme in init() to
add an image once it's loaded.
I am having problems running the CamanJS script on mobile devices, i.e. iPad and iPhone's Safari / Chrome, and I've been trying to resolve it for days.
The test script is very simple:
1) Accepts browser file selection of image
2) Gets the image source using FileData, then drawing it into a canvas, then instantiate a Caman("#sample") object
3) Run some filter (either within onLoad of that image, or manually by clicking a button)
It works perfectly fine on all desktop browsers and the filters are also successfully applied, but when I try it on mobile devices like iOS Safari, the moment I try to instantiate the Caman object, my existing canvas #sample goes blank and reverts to the original canvas default background color, with no image loaded at all. I've tried instantiating the Caman object before image is drawn on canvas, image onLoad, or on demand after the canvas image is successfully drawn, but the end result is still the same - the canvas goes blank.
Below is my sample code, can someone please advise? Thank you for your kind assistance.
<script>
var caman = null;
function handleUpload(evt) {
var target = (evt.target) ? evt.target : evt.srcElement;
var files = target.files; // FileList object
var field = target.id;
var curCount = target.id.replace(/\D+/, "");
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
renderImage(e.target.result);
};
})(f);
reader.readAsDataURL(f);
}
}
function renderImage(imagedata) {
var canvas = document.getElementById("sample");
var ctx = canvas.getContext("2d");
// Render Preview
var previewImage = new Image();
previewImage.src = imagedata;
previewImage.onload = function() {
ctx.drawImage(previewImage, 0, 0, previewImage.width, previewImage.height);
caman = Caman("#sample", function () { this.sunrise().render(); });
};
}
function testProcess() {
//caman = Caman("#sample", function () { this.sunrise().render(); });
if (caman) {
caman.sunrise().render();
}
}
</script>
<form>
<input id="photo" name="photo" value="" type=file size="30" maxlength="50">
</form>
<canvas id="sample" width=300 height=300 style="background-color: #aaaaaa;"></canvas>
<br><br>Test Process<br><br>
<script>
document.getElementById('photo').addEventListener('change', handleUpload, false);
</script>
I had the same problem: worked on Chrome and Safari on my Mac, but did not work on Chrome or Safari on the iPhone 5s running iOS7. I solved by adding the data-caman-hidpi-disabled attribute to my canvas tag.
Try this:
<canvas id="sample" width=300 height=300 style="background-color: #aaaaaa;" data-caman-hidpi-disabled="true"></canvas>
According to the CamanJS website:
If a HiDPI display is detected, CamanJS will automatically switch to
the HiDPI version if available unless you force disable it with the
data-caman-hidpi-disabled attribute.
http://camanjs.com/guides/#BasicUsage