My friend and I are trying to add images to a canvas using JavaScript; however we have no clue how to even do that and we've tried every possible string of code involving drawing images (such as ones from google, etc), all with failure and we don't even know which direction is the right one to take at this point. Can anyone help? Thanks!
Here's a basic example of what you're seeking.
document.getElementById('inp').onchange = function(e) {
var img = new Image();
img.onload = draw;
img.onerror = failed;
img.src = URL.createObjectURL(this.files[0]);
};
function draw() {
var canvas = document.getElementById('canvas');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0,0);
}
function failed() {
console.error("The provided file couldn't be loaded as an Image media");
}
<input type="file" id="inp">
<canvas id="canvas"></canvas>
I need to compress the image on upload keeping the original dimensions of image. I have used Intervention package of Laravel and am successful in compressing the image size, but, the resize() function also changes dimensions. Is it possible to just reduce the size of image without changing the dimensions?
Referring to the documentation of Intervention, you can resize while maintaining the aspect ratio:
// resize the image to a width of 300 and constrain aspect ratio (auto height)
$img->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});
Read the files using the HTML5 FileReader API with .readAsArrayBuffer
Create e Blob with the file data and get its url with
window.URL.createObjectURL(blob)
Create new Image element and set it's src to the file blob url
Send the image to the canvas. The canvas size is set to desired output size
Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
On backend, read the dataURI, decode from Base64, and save it
var fileinput = document.getElementById('fileinput');
var max_width = fileinput.getAttribute('data-maxwidth');
var max_height = fileinput.getAttribute('data-maxheight');
var preview = document.getElementById('preview');
var form = document.getElementById('form');
function processfile(file) {
if( !( /image/i ).test( file.type ) )
{
alert( "File "+ file.name +" is not an image." );
return false;
}
// read the files
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
// blob stuff
var blob = new Blob([event.target.result]); // create blob...
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob); // and get it's URL
// helper Image object
var image = new Image();
image.src = blobURL;
//preview.appendChild(image); // preview commented out, I am using the canvas instead
image.onload = function() {
// have to wait till it's loaded
var resized = resizeMe(image); // send it to canvas
var newinput = document.createElement("input");
newinput.type = 'hidden';
newinput.name = 'images[]';
newinput.value = resized; // put result from canvas into new hidden input
form.appendChild(newinput);
}
};
}
function readfiles(files) {
// remove the existing canvases and hidden inputs if user re-selects new pics
var existinginputs = document.getElementsByName('images[]');
var existingcanvases = document.getElementsByTagName('canvas');
while (existinginputs.length > 0) { // it's a live list so removing the first element each time
// DOMNode.prototype.remove = function() {this.parentNode.removeChild(this);}
form.removeChild(existinginputs[0]);
preview.removeChild(existingcanvases[0]);
}
for (var i = 0; i < files.length; i++) {
processfile(files[i]); // process each file at once
}
fileinput.value = ""; //remove the original files from fileinput
// TODO remove the previous hidden inputs if user selects other files
}
// this is where it starts. event triggered when user selects files
fileinput.onchange = function(){
if ( !( window.File && window.FileReader && window.FileList && window.Blob ) ) {
alert('The File APIs are not fully supported in this browser.');
return false;
}
readfiles(fileinput.files);
}
// === RESIZE ====
function resizeMe(img) {
var canvas = document.createElement('canvas');
var width = img.width;
var height = img.height;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > max_width) {
//height *= max_width / width;
height = Math.round(height *= max_width / width);
width = max_width;
}
} else {
if (height > max_height) {
//width *= max_height / height;
width = Math.round(width *= max_height / height);
height = max_height;
}
}
// resize the canvas and draw the image data into it
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
preview.appendChild(canvas); // do the actual resized preview
return canvas.toDataURL("image/jpeg",0.7); // get the data from canvas as 70% JPG (can be also PNG, etc.)
}
I am using the following code to grab an image from URL and convert it into Base64:
function convertImgToBase64(url, callback){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL();
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
convertImgToBase64(INSER_URL_HERE, function(base64Img){
$("#data_url").text(base64Img);
imageRef.set(base64Img);
});
I am thoroughly confused. So far, the code works and img.onload is fired ONLY when I have tested it using images from Wikipedia (e.g. http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png)! All other external image URLs I have tried do not fire img.onload (e.g. http://www.ipadenclosures.com/php-oak/themes/global/admin_images/Apple_gray_logo.png). Any ideas why these images are not loading?
tried searching for something like this, but I've had no luck. I'm trying to open a new tab with a screenshot of the current state of my webgl image. Basically, it's a 3d model, with the ability to change which objects are displayed, the color of those objects, and the background color. Currently, I am using the following:
var screenShot = window.open(renderer.domElement.toDataURL("image/png"), 'DNA_Screen');
This line succeeds in opening a new tab with a current image of my model, but does not display the current background color. It also does not properly display the tab name. Instead, the tab name is always "PNG 1024x768".
Is there a way to change my window.open such that the background color is shown? The proper tab name would be great as well, but the background color is my biggest concern.
If you open the window with no URL you can access it's entire DOM directly from the JavaScript that opened the window.
var w = window.open('', '');
You can then set or add anything you want
w.document.title = "DNA_screen";
w.document.body.style.backgroundColor = "red";
And add the screenshot
var img = new Image();
img.src = someCanvas.toDataURL();
w.document.body.appendChild(img);
Well it is much longer than your one liner but you can change the background color of the rectangle of the context.
printCanvas (renderer.domElement.toDataURL ("image/png"), width, height,
function (url) { window.open (url, '_blank'); });
// from THREEx.screenshot.js
function printCanvas (srcUrl, dstW, dstH, callback)
{
// to compute the width/height while keeping aspect
var cpuScaleAspect = function (maxW, maxH, curW, curH)
{
var ratio = curH / curW;
if (curW >= maxW && ratio <= 1)
{
curW = maxW;
curH = maxW * ratio;
}
else if (curH >= maxH)
{
curH = maxH;
curW = maxH / ratio;
}
return { width: curW, height: curH };
}
// callback once the image is loaded
var onLoad = function ()
{
// init the canvas
var canvas = document.createElement ('canvas');
canvas.width = dstW;
canvas.height = dstH;
var context = canvas.getContext ('2d');
context.fillStyle = "black";
context.fillRect (0, 0, canvas.width, canvas.height);
// scale the image while preserving the aspect
var scaled = cpuScaleAspect (canvas.width, canvas.height, image.width, image.height);
// actually draw the image on canvas
var offsetX = (canvas.width - scaled.width ) / 2;
var offsetY = (canvas.height - scaled.height) / 2;
context.drawImage (image, offsetX, offsetY, scaled.width, scaled.height);
// notify the url to the caller
callback && callback (canvas.toDataURL ("image/png")); // dump the canvas to an URL
}
// Create new Image object
var image = new Image();
image.onload = onLoad;
image.src = srcUrl;
}
I'd like to know if there is a way to dynamically modify/access the data contained in html images just as if they were an html5 canvas element. With canvas, you can in javascript access the raw pixel data with getImageData() and putImageData(), but I have thus far been not able to figure out how to do this with images.
// 1) Create a canvas, either on the page or simply in code
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 2) Copy your image data into the canvas
var myImgElement = document.getElementById('foo');
ctx.drawImage( myImgElement, 0, 0 );
// 3) Read your image data
var w = myImgElement.width, h=myImgElement.height;
var imgdata = ctx.getImageData(0,0,w,h);
var rgba = imgdata.data;
// 4) Read or manipulate the rgba as you wish
for (var px=0,ct=w*h*4;px<ct;px+=4){
var r = rgba[px ];
var g = rgba[px+1];
var b = rgba[px+2];
var a = rgba[px+3];
}
// 5) Update the context with newly-modified data
ctx.putImageData(imgdata,0,0);
// 6) Draw the image data elsewhere, if you wish
someOtherContext.drawImage( ctx.canvas, 0, 0 );
Note that step 2 can also be brought in from an image loaded directly into script, not on the page:
// 2b) Load an image from which to get data
var img = new Image;
img.onload = function(){
ctx.drawImage( img, 0, 0 );
// ...and then steps 3 and on
};
img.src = "/images/foo.png"; // set this *after* onload
You could draw the image to a canvas element with drawImage(), and then get the pixel data from the canvas.
After having some issues with this code, I want to add one or two things to Phrogz's answer :
// 1) Create a canvas, either on the page or simply in code
var myImgElement = document.getElementById('foo');
var w = myImgElement.width, h=myImgElement.height; // New : you need to set the canvas size if you don't want bug with images that makes more than 300*150
var canvas = document.createElement('canvas');
canvas.height = h;
canvas.width = w;
var ctx = canvas.getContext('2d');
// 2) Copy your image data into the canvas
ctx.drawImage( myImgElement, 0, 0, w, h ); // Just in case...
// 3) Read your image data
var imgdata = ctx.getImageData(0,0,w,h);
var rgba = imgdata.data;
// And then continue as in the other code !
that worked for me (IE10x64,Chromex64 on win7, chromium arm linux, ...seems to bug with firefox 20 arm linux but not sure ... to re-test)
--html--
<canvas id="myCanvas" width="600" height="300"></canvas>
<canvas id="myCanvasOffscreen" width="1" height="1"></canvas>
-- js --
// width & height can be used to scale image !!!
function getImageAsImageData(url, width, height, callack) {
var canvas = document.getElementById('myCanvasOffscreen');
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0, width, height);
imgData = context.getImageData(0,0,width, height);
canvas.width = 1;
canvas.height = 1;
callack( imgData );
};
imageObj.src = url;
}
-- then --
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var imgData;
getImageAsImageData('central_closed.png', IMG_WIDTH, IMG_HEIGHT,
function(imgData) {
// do what you want with imgData.data (rgba array)
// ex. colorize( imgData, 25, 70, 0);
ctx.putImageData(imgData,0,0);
}
);
you first want to draw a pic on the canvas and then get the imageData from the canvas ,it is a wrong way,because the js think it is a "Cross-domain access",but the getIamgeData method don't allow the "Cross-domain access" to an image.you can hava a try by put the in the root place and access it by "localhost" .
Im not sure if it is possible, but you can try requesting pixel information from PHP, if GD library it will be an easy task, but surely will be slower. Since you didnt specified application so I will suggest checking SVG for this task if they can be vector images than you will be able to query or modify the image.
Directly work on IMG element is also valid:
var image = document.createElement('img'),w,h ;
image.src = "img/test.jpg" ;
$(image).one('load',function(){
w = image.naturalWidth ;
h = image.naturalHeight ;
var cnv = document.createElement('canvas') ;
$(cnv).attr("width",w) ;
$(cnv).attr("height",h) ;
var ctx = cnv.getContext('2d') ;
ctx.drawImage(image,0,0) ;
var imgdata = ctx.getImageData(0,0,w,h) ;
var rgba = imgdata.data ;
for (var px=0,ct=w*h*4;px<ct;px+=4){
var r = rgba[px+0] ;
var g = rgba[px+1] ;
var b = rgba[px+2] ;
var a = rgba[px+3] ;
// Do something
rgba[px+0] = r ;
rgba[px+1] = g ;
rgba[px+2] = b ;
rgba[px+3] = a ;
}
ctx.putImageData(imgdata,0,0) ;
$("body").append(cnv) ;
}) ;