image url to canvas and save - javascript

I am trying to load an image from a URL to the canvas, and then display the image to be saved. I can display the image in the canvas but when I trying to display the image as a base64 string it it blank. Here is what I can come up with so far just need help on the last part.
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'http://3.bp.blogspot.com/-4NP3xwj-ZMI/UXU8RT1k02I/AAAAAAAACEU/88knXDu2MeQ/s72-c/music3g1.JPG';
var dataURL = canvas.toDataURL();
document.getElementById('canvasImg').src = dataURL;

Okay, a couple of things to know.
When you draw an image to a canvas from a source outside of the domain the html is in, it flags the dirty flag on the canvas. This makes it so you can't use the .toDataURL() function. It is mainly a security issue.
var dataURL = canvas.toDataURL(); document.getElementById('canvasImg').src = dataURL; is called before the image is actually drawn to the canvas. You'll need to get the data url and set the src within the onload function of the image.

Related

Blank image when executing canvas.toDataUrl()

Go to this website.
Open up the console and write:
`
var canvas = $("#mandelbox-canvas")[0];
var imgData = canvas.toDataURL("image/png").split(',')[1];
console.log(imgData);
Copy the data URL and paste into this site.
Why is the image blank? How can I fix this?
Things I have already tried:
I have tried the solution to this question. I.E. This code:
var canvas = $("#mandelbox-canvas")[0];
canvas.getContext('webgl',{preserveDrawingBuffer:true});
var imgData = canvas.toDataURL("image/png").split(',')[1];
console.log(imgData)
however the image is still blank. The image does not contain the image displayed on the canvas.
So after much trawling through StackOverflow I found the function drawScene() which (somehow?) force toDataURL() to return the image data as required:
var canvas = $("#mandelbox-canvas")[0];
drawScene()
var imgData = canvas.toDataURL("image/png").split(',')[1];
console.log(imgData)

chrome.browserAction.setIcon - Downloaded image

I want to make a Chrome addon, which displays ones Facebook picture.
Mine e.g. is this one.
I do get the final Url and the response of an XMLHttpRequest.
In response.response I have the image data, which starts with ����JFIF���Photoshop 3.08BIM�gO87swNzt0qHGr_stQXIz(bFBMD01000aa00100001d020000b6020000ec02000027030
I am trying to store and than display it. (I want to display this bigger on a different place as well). So I do not want to use path in chrome.browserAction.setIcon, but the Image itself.
I tried a lot of things (and will continue tomorrow). So far:
I need an ImageData Object
I need an ImageData Object smaller than <= 19 pixels.
I do know the size of the image from facebook (50x50)
Tomorrow I will continue with trying this. I forgot, that the Image is not base64 encoded yet, so the solution linked in this sentence was not able to work...
My problem is: How to create the ImageData-Object(s) required by chrome.browserAction.setIcon frim the icon above in JS. Using the "html5-canvas" tag, as ImageData is very close to a canvas.
As always, answers are highly appreciated.
Yours,
Florian
facebook graph API does send the proper Access-Control-Allow-Origin "*" in the header of the image's response.
So all you need is to set the crossorigin attribute of an <img> tag to 'anonymous', draw this image onto a canvas and use either the imageData you get from ctx.getImageData() or the dataURI you get from canvas.toDataURL().
var c = document.createElement('canvas');
var ctx = c.getContext('2d')
var img = new Image();
img.crossOrigin = 'anonymous';
img.onload = function(){
c.width = this.width;
c.height = this.height;
ctx.drawImage(this, 0,0);
// either you do use the image data
var imagedata = ctx.getImageData(0,0,c.width, c.height);
snippet.log('imagedata length : '+imagedata.data.length);
// or the dataURL
var dataURL = c.toDataURL();
snippet.log(dataURL);
document.body.style.backgroundImage = 'url('+dataURL+')';
}
img.src = "https://graph.facebook.com/100004288501341/picture?type=square"
p{background-color: rgba(230, 230, 250,.7);}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

AngularJS save and display image from URL

I wish to create a simple function in angularJS so I can read image from URL. Simply I put image URL and it convert image of that URL to base64 and saves to DB as well it shows to that Image Canvas. I wish to read image of all type irrespective of only PNG.
I have tried few logics, from Google I found code where it takes dimensions of canvas first..
$scope.convertBase64 = function () {
console.log("Firing Function");
var canvas = $scope.imageURL;
canvas.width = $scope.imageURL.width;
canvas.height = $scope.imageURL.height;
var ctx = canvas.getContext("2d");
ctx.drawImage($scope.imageURL, 0, 0);
var dataURL = canvas.toDataURL("image/png");
$scope.imageURLBase = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
return $scope.imageURLBase;
};
At same moment I wish to save image's base64 content. How to render using that base64 content anytime irrespective of canvas size using ng-source or else.

Loading client's images into a canvas

I have been searching this website for answers to this question, but I couldn't seem to find any. So I want to have the client provide an image to be loaded into a canvas for processing and that's it. So I don't want to save it on the server or on a cloud, but I just want to copy the image to an HTML5 Canvas to be processed from there. Is there a way I can do that without actually saving the file?
I'm not sure if I understand your question. You want that the user can open an image from the client and you load it into a html5 canvas. correct?
If so: you can use an input field of type file. In your code you use URL.createObjectUrl to create object urls from the local selected images. With "Image" you can load the image and in the onload event you draw it to the canvas.
var file = document.getElementById('file'); // the input element of type file
file.onchange = function(e) {
var ctx = document.getElementById('canvas').getContext('2d'); // load context of canvas
var img = new Image();
img.src = URL.createObjectURL(e.target.files[0]); // use first selected image from input element
img.onload = function() {
ctx.drawImage(img, 0, 0); // draw the image to the canvas
}
}

Canvas toDataUrl increases file size of image

When using toDataUrl() to set the source of an image tag I am finding that the image when saved is a great deal larger than the original image.
In the example below I am not specifying a second param for the toDataUrl function so the default quality is being used. This is resulting in an image much larger that the original image size. When specifying 1 for full quality the image generated is even larger.
Does anybody know why this is happening or how I can stop it?
// create image
var image = document.createElement('img');
// set src using remote image location
image.src = 'test.jpg';
// wait til it has loaded
image.onload = function (){
// set up variables
var fWidth = image.width;
var fHeight = image.height;
// create canvas
var canvas = document.createElement('canvas');
canvas.id = 'canvas';
canvas.width = fWidth;
canvas.height = fHeight;
var context = canvas.getContext('2d');
// draw image to canvas
context.drawImage(image, 0, 0, fWidth, fHeight, 0, 0, fWidth, fHeight);
// get data url
dataUrl = canvas.toDataURL('image/jpeg');
// this image when saved is much larger than the image loaded in
document.write('<img src="' + dataUrl + '" />');
}
Thank you :D
Here is an example, unfortunately the image cannot be cross domain and so I am having to just pull one of the jsfiddle images.
http://jsfiddle.net/ptSUd/
The image is 7.4kb, if you then save the image which is being output you will see that it is 10kb. The difference is more noticeable with more detailed images. If you set the toDataUrl quality to 1, the image is then 17kb.
I am also using FireFox 10 for this, when using Chrome the image sizes are still larger but not by as much.
The string returned by the toDataURL() method does not represent the original data.
I have just performed some extensive tests, which showed that the created data-URL depends on the browser (not on the operating system).
Environment - md5 sum - file size
Original file - c9eaf8f2aeb1b383ff2f1c68c0ae1085 - 4776 bytes
WinXP Chrome 17.0.963.79 - 94913afdaba3421da6ddad642132354a - 7702 bytes
Linux Chrome 17.0.963.79 - 94913afdaba3421da6ddad642132354a - 7702 bytes
Linux Firefox 10.0.2 - 4f184006e00a44f6f2dae7ba3982895e - 3909 bytes
The method of getting the data-URI does not matter, the following snippet was used to verify that the data-URI from a file upload are also different:
Test case: http://jsfiddle.net/Fkykx/
<input type="file" id="file"><script>
document.getElementById('file').onchange=function() {
var filereader = new FileReader();
filereader.onload = function(event) {
var img = new Image();
img.onload = function() {
var c = document.createElement('canvas'); // Create canvas
c.width = img.width;
c.height = img.height; c.getContext('2d').drawImage(img,0,0,img.width,img.height);
var toAppend = new Image;
toAppend.title = 'Imported via upload, drawn in a canvas';
toAppend.src = c.toDataURL('image/png');
document.body.appendChild(toAppend);
}
img.src = event.target.result; // Set src from upload, original byte sequence
img.title = 'Imported via file upload';
document.body.appendChild(img);
};
filereader.readAsDataURL(this.files[0]);
}
</script>
The size of the image is determined mostly by the quality of the encoder built into the browser. It has very little to do with the size of the original image. Once you draw anything onto a canvas all you have are pixels, you no longer have the original image. toDataURL does not magically reconstitute an image that was painted onto the canvas. If you want a file with the same size as the original image: use the original image.
Looks like kirilloid and Rob nailed it. I had this issue too and it appears to be a combo:
the dataURL uses base64 encoding which makes it around 1.37 X larger
each browser processes the toDataURL function differently
base64 encoded image size
I tested my thumbnail generator in win8.1 firefox and chrome and got dataURL string sizes:
firefox = 3.72kB
chrome = 3.24kB
My original image when converted to dataURL went from 32kB to 45kB.
I think the base64 part is the larger factor so I guess my plan now is to convert the dataURL back to a binary byte array before I store it on the server (probably on the client side because my server's lazy).

Categories