Dynamic videos from user inputs - How does it work? - image

Is there a way to generate a video frame's content by code?
For example :
I want to make a program that takes some string variable as input and then gives an output video of same text but now with special effects on the text itself.
It came to my mind the idea after seeing some projects that Facebook has done in their website. They have a database of pictures, comments, friends, events, likes and so on, that are related to a User. With all this information they do videos like for example Friend's day, a video that is completely related to the user that wants to post it.
How does these things work?
Is there some sort of software I can use? Can someone give me a place to start with?

I want to make a program that takes some string variable as input and then gives an output video of same text but now with special effects on the text itself.
You can render the text using canvas and record the result using the new Media Recorder API.
The effects can be made various ways of course, and the text content itself can be used against a database, or in conjunction with machine learning to structure/obtain some data relative to the text. This has a wide scope though, wider than what fits in here.
In any case, the generation of the video itself is shown below. It is a simple example where you can enter some text, it gets animated and recorded as video. When you click stop the actual video will show instead (which you can allow user to download). You can extend with other effects, storyboard features so you can record scenes and develop it to make an entire movie.
Do notice that all animation happens on the canvas in real-time. Typical video is recorded at 30 frames per second and not 60 frames per second, which is the typical frame rate for canvas. This is also something to consider in regard to smoothness. However, you can use this to your advantage by targeting 30 FPS to give your code a little more time to process. The API is suppose to support step-recording by not giving a frame rate as argument, but I have not been able to make this work as of yet.
There are currently limits with support of the API as not all browsers supports it yet.
Example
// un-refined code for demo use only
// set up globals, get key elements
var div = document.querySelector("div");
var btn = document.querySelector("button");
var txt = document.querySelector("input");
var c = document.querySelector("canvas");
// make 2d context without alpha channel
var ctx = c.getContext("2d", {alpha: false});
var isRecording = false;
// stream vars
var rec, stream, tref;
// if clicked, lets go
btn.onclick = setup;
function setup() {
// toggle button text/status for demo
if (isRecording) {
this.disabled = true;
this.innerHTML = "Making video...";
stop();
return
}
else {
isRecording = true;
this.innerHTML = "Click to stop & show video";
}
// Setup canvas for text rendering
var ct1 = document.createElement("canvas");
var ct2 = document.createElement("canvas");
var ctxText1 = ct1.getContext("2d");
var ctxText2 = ct2.getContext("2d");
var w, h;
w = ct1.width = ct2.width = c.width;
h = ct1.height = ct2.height = c.height;
setupCtx(ctxText1, "#333", "#FF9F05");
setupCtx(ctxText2, "#FF9F05", "#000");
function setupCtx(ctxText, bg, fg) {
ctxText.textAlign = "center";
ctxText.textBaseline = "middle";
ctxText.font = "92px sans-serif";
ctxText.fillStyle = bg;
ctxText.fillRect(0, 0, w, h);
ctxText.fillStyle = fg;
ctxText.translate(w/2, h/2);
ctxText.rotate(-0.5);
ctxText.fillText(txt.value.toUpperCase(), 0, 0);
}
// populate grid (see Square object below which handles the tiles)
var cols = 18,rows = 11,
cellWidth = (c.width / cols)|0,
cellHeight = (c.height / rows)|0,
grid = [],
len = cols * rows, y = 0, x,
index, hasActive = true;
for (; y < rows; y++) {
for (x = 0; x < cols; x++) {
grid.push(new Square(ctx, x * cellWidth, y * cellHeight, cellWidth, cellHeight, ct1, ct2, 0.01));
}
}
x = 0;
// start recording canvas to video
record();
//animation loop (refactor at will)
function loop() {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
ctx.clearRect(0, 0, w, h);
// trigger cells
for (y = 0; y < rows; y++) {
var gx = (x | 0) - y;
if (gx >= 0 && gx < cols) {
index = y * cols + gx;
grid[index].trigger();
}
}
x += 0.25;
// update all
for (var i = 0; i < grid.length; i++) grid[i].update();
tref = requestAnimationFrame(loop);
}
// setup media recorder to record canvas # 30 FPS (note: canvas = 60 FPS by def.)
function record() {
stream = c.captureStream(30);
rec = new MediaRecorder(stream);
rec.addEventListener('dataavailable', done);
rec.start();
requestAnimationFrame(loop);
}
}
// stop recorder and trigger dataavailable event
function stop() {
rec.stop();
cancelAnimationFrame(tref); // stop loop as well
}
// finish up, show new shiny video instead of canvas
function done(e) {
var blob = new Blob([e.data], {"type": "video/webm"});
var video = document.createElement("video");
document.body.removeChild(c);
document.body.appendChild(video);
// play, Don
video.autoplay = video.loop = video.controls = true;
video.src = URL.createObjectURL(blob);
video.onplay = function() {
div.innerHTML = "Playing resulting video below:";
};
}
// stolen from a previous example I made (CC3.0-attr btw as always)
// this is included for the sole purpose of some animation.
function Square(ctx, x, y, w, h, image, image2, speed) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.height = h;
this.width = w;
this.image = image;
this.image2 = image2;
this.first = true;
this.alpha = 0; // current alpha for this instance
this.speed = speed; // increment for alpha per frame
this.triggered = false; // is running
this.done = false; // has finished
}
Square.prototype = {
trigger: function () { // start this rectangle
this.triggered = true
},
update: function () {
if (this.triggered && !this.done) { // only if active
this.alpha += this.speed; // update alpha
if (this.alpha <= 0 || this.alpha >= 1)
this.speed = -this.speed;
}
var t = Math.sin(Math.PI * this.alpha);
if (t <= 0) this.first = !this.first;
this.ctx.fillStyle = this.color; // render this instance
this.ctx.globalAlpha = Math.max(0, Math.min(1, t));
var cx = this.x + this.width * 0.5, // center position
cy = this.y + this.width * 0.5;
this.ctx.setTransform(t*0.5+0.5, 0, 0, t*0.5+0.5, cx, cy); // scale and translate
this.ctx.rotate(-Math.PI * (1 - t)); // rotate, 90° <- alpha
this.ctx.translate(-cx, -cy); // translate back
this.ctx.drawImage(this.first ? this.image : this.image2, this.x, this.y, this.width, this.height, this.x, this.y, this.width, this.height);
}
};
body {background: #555;color:#ddd;font:16px sans-serif}
<div>
<label>Enter text to animate: <input value="U R AWESOME"></label>
<button>Click to start animation + recording</button>
</div>
<canvas width=640 height=400></canvas>

Related

html5 canvas large sprite sheet image animation performance optimization

I am using the method from
http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
to render sprite sheet animation on canvas
and it works fine mostly
But when the sprite sheet image is large, (30000*500, 60 frames png file in my case) the performance is so bad especially on Android webview.
I think the image resource tooks too much memory, but how do I optimize its memory usage ? I've tried compress the image by "ImageOptim", but it didn't make any noticeable difference.
Can someone give me some advices about performance optimization when rendering large sprite sheet on canvas ?
Use ImageBitmaps.
Your image is probably too big to be held in the graphic cards memory, this means that every time it has to be moved there again, which may makes things really slow indeed.
ImageBitmap objects allow to keep the raw bitmap data ready to be used by the GPU with no extra.
So at init, you'd prepare your ImageBitmaps and throw away the full image.
Now only small bitmaps ready to be put would get passed to the GPU.
async function initSprites( img, sprite_width = img.width, sprite_height = img.height ) {
// you would have to make the sprite factory logic based on your actual spritesheet,
// here Im using a simple fixed-size grid from wikimedia
const sprites = [];
for( let y = 0; y < img.height; y += sprite_height) {
for( let x = 0; x < img.width; x += sprite_width ) {
sprites.push(
await createImageBitmap( img, x, y, sprite_width, sprite_height )
);
}
}
return sprites;
}
async function loadImage( url ) {
var img = new Image();
img.crossOrigin = 'anonymous';
await new Promise( (res, rej) => {
img.onload = (e) => res( img );
img.onerror = rej;
img.src = url;
} );
return img;
}
async function init() {
const url = "https://upload.wikimedia.org/wikipedia/commons/b/be/SpriteSheet.png";
const FPS = 10;
const sprite_width = 132;
const sprite_height = 97;
// we don't keep any reference to the Image
const sprites = await initSprites( await loadImage( url ), sprite_width, sprite_height );
const canvas = document.getElementById( 'canvas' );
const ctx = canvas.getContext( '2d' );
const frame_time = 1000 / FPS;
let sprite_index = 0;
let lastTime = performance.now();
requestAnimationFrame( update );
function update( t ) {
if( t - lastTime > frame_time ) {
lastTime = t;
sprite_index = (sprite_index + 1) % sprites.length;
draw();
}
requestAnimationFrame( update );
}
function draw() {
ctx.clearRect( 0, 0, canvas.width, canvas.height );
// we just reproduce the original spritesheet
// but animated
let inner_index = 0;
for(let y = 0; y < 3; y++) {
for( let x = 0; x < 4; x ++ ) {
inner_index ++;
const index = (sprite_index + inner_index) % sprites.length;
const sprite = sprites[ index ];
ctx.drawImage( sprite, x * sprite_width, y * sprite_height );
}
}
}
}
// for Safari and IE
monkeyPatchCreateImageBitmap();
init().catch( console.error );
// a very poor monkey patch, only allowing HTMLImageElement as source
// returns an HTMLCanvasElement
function monkeyPatchCreateImageBitmap() {
if( typeof window.createImageBitmap === 'undefined' ) {
window.createImageBitmap = monkeyPatch;
}
function monkeyPatch( img, sx = 0 , sy = 0, sw = img.width, sh = img.height ){
const canvas = document.createElement( 'canvas' );
canvas.width = sw;
canvas.height = sh;
canvas.getContext( '2d' )
.drawImage( img, sx, sy, sw, sh, 0, 0, sw, sh );
canvas.close = (e) => canvas.width = 0;
return Promise.resolve( canvas );
};
}
<canvas id="canvas" width="528" height="291"></canvas>

Move an object between two ml5js poseNet keypoints using p5js

I'm trying to make a circle move between two body keypoints – i.e between left and right shoulder. I started with this code to make an object following some position:
var rectLocation;
var x = 50;
var y = 50;
function setup() {
createCanvas(640,400);
rectLocation = createVector(width/2,height/2);
}
function draw() {
background(255);
var target = createVector(x,y);
var distance = target.dist(rectLocation);
var mappedDistance = map(distance, 100, 0, 1.5, 0.5);
target.sub(rectLocation);
target.normalize();
target.mult(mappedDistance);
rectLocation.add(target);
text('hello',rectLocation.x, rectLocation.y);
x = x + 1 ;
if (x > width) {
x = 50;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
So with poseNet I converted x and y values of each keypoint into p5 Vectors and made one location follow another, but it doesn't seem to move and I can't get why. Sketch: https://editor.p5js.org/sebyakin/sketches/LQ7gqwGZH and my code here:
let video;
let poseNet;
let noseX = 0;
let noseY = 0;
let eyelX = 0;
let eyelY = 0;
let shoulderX = 0;
let shoulderY = 0;
let firstLocation;
let target;
function setup() {
createCanvas(640, 480);
video = createCapture(VIDEO);
video.hide();
poseNet = ml5.poseNet(video, modelReady);
poseNet.on('pose', gotPoses);
// creating empty vectors
firstLocation = createVector(0,0);
target = createVector(0,0);
}
function gotPoses(poses) {
if (poses.length > 0) {
let nX = poses[0].pose.keypoints[0].position.x;
let nY = poses[0].pose.keypoints[0].position.y;
let eX = poses[0].pose.keypoints[1].position.x;
let eY = poses[0].pose.keypoints[1].position.y;
let sX = poses[0].pose.keypoints[5].position.x;
let sY = poses[0].pose.keypoints[5].position.y;
noseX = nX;
noseY = nY;
eyelX = eX;
eyelY = eY;
shoulderX = sX;
shoulderY = sY;
}
}
function modelReady() {
console.log('model ready');
}
function draw() {
image(video, 0, 0);
fill(0,0,255);
// set vectors to keypoints values
firstLocation.set(noseX, noseY);
target.set(shoulderX, shoulderY)
// make a circle follow target loaction
let distance = target.dist(firstLocation);
let mappedDistance = map(distance, 100, 0, 1.5, 0.5);
target.sub(firstLocation);
// target.normalize();
// target.mult(mappedDistance);
firstLocation.add(target);
ellipse(firstLocation.x, firstLocation.y, 50);
console.log(target.x);
}
Where did I go wrong?

Three.js and applying texture

I'm using a neat script found online (Teal 3d dice roller).
http://a.teall.info/dice/
The dice numbers are hardcoded as standard fonts in the script (no image textures applied).
I would like to get rid of those numbers and apply pictogram textures instead to customize the dice to fit my needs.
So, right now, I'm just trying to apply one unique texture to all faces (even though I plan to obviously have 6 different textures eventually but first thing first).
Here is the original script function :
this.create_dice_materials = function(face_labels, size, margin) {
function create_text_texture(text, color, back_color) {
/* --- start of the part I planned to modify --- */
if (text == undefined) return null;
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var ts = calc_texture_size(size + size * 2 * margin) * 2;
canvas.width = canvas.height = ts;
context.font = ts / (1 + 2 * margin) + "pt Arial";
context.fillStyle = back_color;
context.fillRect(0, 0, canvas.width, canvas.height);
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = color;
context.fillText(text, canvas.width / 2, canvas.height / 2);
/* --- End of the part I planned to modify --- */
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
return texture;
}
var materials = [];
for (var i = 0; i < face_labels.length; ++i)
materials.push(new THREE.MeshPhongMaterial($t.copyto(this.material_options,
{ map: create_text_texture(face_labels[i], this.label_color, this.dice_color) })));
return materials;
}
And here is my attempt to apply a texture instead:
this.create_dice_materials = function(face_labels, size, margin) {
function create_text_texture(text, color, back_color) {
/* --- start of the modified part --- */
var img = document.getElementById("image_name");
var canvas = document.createElement("canvas");
var cs = img.height;
canvas.width = img.height;
canvas.height = img.height;
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0, cs, cs, 0, 0, cs, cs);
/* --- End of the modified part --- */
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
return texture;
}
var materials = [];
for (var i = 0; i < face_labels.length; ++i)
materials.push(new THREE.MeshPhongMaterial($t.copyto(this.material_options,
{ map: create_text_texture(face_labels[i], this.label_color, this.dice_color) })));
return materials;
}
Note: the texture picture is embedded within the html file as an img tag. It shows up alright as a flat html picture and it has the proper id which is "image_name". So, this shouldn't be part of the problem.
Anyway, those changes in the script don't break the script (no exception appears in the console while executing it),but nothing shows up on the dice neither. No numbers, no texture.
Any idea what is wrong and how I should proceed to make it work?
So far I suspect two things:
1) the "drawImage" parameters
2) the "map" parameter within the materials array
Thanks.
For whatever reason, it worked on a distant server, not locally.
So, I guess it is solved.

What did google play music use to create the "particles" visualiser on their website?

What does google play music use to create the "particles" visualiser on their website?
What 3D graphic software was used? My guess was originally unity 3D exported via webGL, or perhaps three.js or UE4?
I don't understand how they get the audio web player to stream the audio while the 3D visualiser reacts to the audio frequencies.
I wanted to re-create the same thing. Not sure where to start. I lack the knowledge on how it is done.
Couldn't find any answers on the web.
Most importantly are there different methods doing what google has done. What are the main differences?
Link of Visualiser demonstration: https://www.youtube.com/watch?v=mjfKCSPFdGI
Thanks.
It would be nice if you'd post a gif or something to show what you're referring to.
Making something audio reactive is pretty simple though. Here's an open source site with lots audio reactive examples.
As for how to do it you basically use the Web Audio API to stream the music and use it's AnalyserNode to get audio data out.
"use strict";
const ctx = document.querySelector("canvas").getContext("2d");
ctx.fillText("click to start", 100, 75);
ctx.canvas.addEventListener('click', start);
function start() {
ctx.canvas.removeEventListener('click', start);
// make a Web Audio Context
const context = new AudioContext();
const analyser = context.createAnalyser();
// Make a buffer to receive the audio data
const numPoints = analyser.frequencyBinCount;
const audioDataArray = new Uint8Array(numPoints);
function render() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// get the current audio data
analyser.getByteFrequencyData(audioDataArray);
const width = ctx.canvas.width;
const height = ctx.canvas.height;
const size = 5;
// draw a point every size pixels
for (let x = 0; x < width; x += size) {
// compute the audio data for this point
const ndx = x * numPoints / width | 0;
// get the audio data and make it go from 0 to 1
const audioValue = audioDataArray[ndx] / 255;
// draw a rect size by size big
const y = audioValue * height;
ctx.fillRect(x, y, size, size);
}
requestAnimationFrame(render);
}
requestAnimationFrame(render);
// Make a audio node
var audio = new Audio();
audio.loop = true;
audio.autoplay = true;
// this line is only needed if the music you are trying to play is on a
// different server than the page trying to play it.
// It asks the server for permission to use the music. If the server says "no"
// then you will not be able to play the music
audio.crossOrigin = "anonymous";
// call `handleCanplay` when it music can be played
audio.addEventListener('canplay', handleCanplay);
audio.src = "https://twgljs.org/examples/sounds/DOCTOR%20VOX%20-%20Level%20Up.mp3";
audio.load();
function handleCanplay() {
// connect the audio element to the analyser node and the analyser node
// to the main Web Audio context
const source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
}
}
canvas { border: 1px solid black; display: block; }
<canvas></canvas>
Then it's just up to you to do something creative. For example instead of drawing a bunch of black dots across the screen like the first example we could scale random colored circles and adjust their color and velocity something like this
"use strict";
var context = new AudioContext();
var analyser = context.createAnalyser();
var numPoints = analyser.frequencyBinCount;
var audioDataArray = new Uint8Array(numPoints);
var ctx = document.querySelector("canvas").getContext("2d");
var ctx2 = document.createElement("canvas").getContext("2d");
var numSpots = 5;
var spots = [];
for (var ii = 0; ii < numSpots; ++ii) {
spots.push({
x: Math.random(),
y: Math.random(),
velocity: 0.01,
direction: Math.random(),
hue: Math.random() * 360 | 0,
});
}
function rnd(min, max) {
if (max === undefined) {
max = min;
min = 0;
}
return Math.random() * (max - min) + min;
}
function render() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.save();
ctx.globalAlpha = .97;
ctx.globalCompositeOperation = "source-out";
ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2);
ctx.scale(1.001, 1.001);
ctx.rotate(0.003);
ctx.translate(-ctx.canvas.width / 2, -ctx.canvas.height / 2);
ctx.drawImage(ctx2.canvas, 0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
analyser.getByteFrequencyData(audioDataArray);
const width = ctx.canvas.width;
const height = ctx.canvas.height;
spots.forEach((spot, n) => {
const ndx = n * numPoints / numSpots | 0;
const audioValue = audioDataArray[ndx] / 255;
const sat = Math.pow(audioValue, 2) * 100;
spot.velocity = audioValue * 0.02;
spot.direction = (spot.direction + 1 + rnd(-.01, 0.01)) % 1;
const angle = spot.direction * Math.PI * 2;
spot.x = (spot.x + Math.cos(angle) * spot.velocity + 1) % 1;
spot.y = (spot.y + Math.sin(angle) * spot.velocity + 1) % 1;
ctx.fillStyle = "hsl(" + spot.hue + "," + sat + "%,50%)";
ctx.beginPath();
ctx.arc(spot.x * width, spot.y * height, 50 * audioValue, 0, Math.PI * 2, false);
ctx.fill();
});
var temp = ctx;
ctx = ctx2;
ctx2 = temp;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
var audio = new Audio();
audio.loop = true;
audio.autoplay = true;
// this line is only needed if the music you are trying to play is on a
// different server than the page trying to play it.
// It asks the server for permission to use the music. If the server says "no"
// then you will not be able to play the music
audio.crossOrigin = "anonymous";
audio.addEventListener('canplay', handleCanplay);
audio.loop = true;
audio.src = "https://twgljs.org/examples/sounds/DOCTOR%20VOX%20-%20Level%20Up.mp3";
audio.load();
function handleCanplay() {
const source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
}
canvas { border: 1px solid black; display: block; }
<canvas></canvas>
music: DOCTOR VOX - Level Up

HTML5 Pre-resize images before uploading

Here's a noodle scratcher.
Bearing in mind we have HTML5 local storage and xhr v2 and what not. I was wondering if anyone could find a working example or even just give me a yes or no for this question:
Is it possible to Pre-size an image using the new local storage (or whatever), so that a user who does not have a clue about resizing an image can drag their 10mb image into my website, it resize it using the new localstorage and THEN upload it at the smaller size.
I know full well you can do it with Flash, Java applets, active X... The question is if you can do with Javascript + Html5.
Looking forward to the response on this one.
Ta for now.
Yes, use the File API, then you can process the images with the canvas element.
This Mozilla Hacks blog post walks you through most of the process. For reference here's the assembled source code from the blog post:
// from an input element
var filesToUpload = input.files;
var file = filesToUpload[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e) {img.src = e.target.result}
reader.readAsDataURL(file);
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
//Post dataurl to the server with AJAX
I tackled this problem a few years ago and uploaded my solution to github as https://github.com/rossturner/HTML5-ImageUploader
robertc's answer uses the solution proposed in the Mozilla Hacks blog post, however I found this gave really poor image quality when resizing to a scale that was not 2:1 (or a multiple thereof). I started experimenting with different image resizing algorithms, although most ended up being quite slow or else were not great in quality either.
Finally I came up with a solution which I believe executes quickly and has pretty good performance too - as the Mozilla solution of copying from 1 canvas to another works quickly and without loss of image quality at a 2:1 ratio, given a target of x pixels wide and y pixels tall, I use this canvas resizing method until the image is between x and 2 x, and y and 2 y. At this point I then turn to algorithmic image resizing for the final "step" of resizing down to the target size. After trying several different algorithms I settled on bilinear interpolation taken from a blog which is not online anymore but accessible via the Internet Archive, which gives good results, here's the applicable code:
ImageUploader.prototype.scaleImage = function(img, completionCallback) {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
while (canvas.width >= (2 * this.config.maxWidth)) {
canvas = this.getHalfScaleCanvas(canvas);
}
if (canvas.width > this.config.maxWidth) {
canvas = this.scaleCanvasWithAlgorithm(canvas);
}
var imageData = canvas.toDataURL('image/jpeg', this.config.quality);
this.performUpload(imageData, completionCallback);
};
ImageUploader.prototype.scaleCanvasWithAlgorithm = function(canvas) {
var scaledCanvas = document.createElement('canvas');
var scale = this.config.maxWidth / canvas.width;
scaledCanvas.width = canvas.width * scale;
scaledCanvas.height = canvas.height * scale;
var srcImgData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var destImgData = scaledCanvas.getContext('2d').createImageData(scaledCanvas.width, scaledCanvas.height);
this.applyBilinearInterpolation(srcImgData, destImgData, scale);
scaledCanvas.getContext('2d').putImageData(destImgData, 0, 0);
return scaledCanvas;
};
ImageUploader.prototype.getHalfScaleCanvas = function(canvas) {
var halfCanvas = document.createElement('canvas');
halfCanvas.width = canvas.width / 2;
halfCanvas.height = canvas.height / 2;
halfCanvas.getContext('2d').drawImage(canvas, 0, 0, halfCanvas.width, halfCanvas.height);
return halfCanvas;
};
ImageUploader.prototype.applyBilinearInterpolation = function(srcCanvasData, destCanvasData, scale) {
function inner(f00, f10, f01, f11, x, y) {
var un_x = 1.0 - x;
var un_y = 1.0 - y;
return (f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y);
}
var i, j;
var iyv, iy0, iy1, ixv, ix0, ix1;
var idxD, idxS00, idxS10, idxS01, idxS11;
var dx, dy;
var r, g, b, a;
for (i = 0; i < destCanvasData.height; ++i) {
iyv = i / scale;
iy0 = Math.floor(iyv);
// Math.ceil can go over bounds
iy1 = (Math.ceil(iyv) > (srcCanvasData.height - 1) ? (srcCanvasData.height - 1) : Math.ceil(iyv));
for (j = 0; j < destCanvasData.width; ++j) {
ixv = j / scale;
ix0 = Math.floor(ixv);
// Math.ceil can go over bounds
ix1 = (Math.ceil(ixv) > (srcCanvasData.width - 1) ? (srcCanvasData.width - 1) : Math.ceil(ixv));
idxD = (j + destCanvasData.width * i) * 4;
// matrix to vector indices
idxS00 = (ix0 + srcCanvasData.width * iy0) * 4;
idxS10 = (ix1 + srcCanvasData.width * iy0) * 4;
idxS01 = (ix0 + srcCanvasData.width * iy1) * 4;
idxS11 = (ix1 + srcCanvasData.width * iy1) * 4;
// overall coordinates to unit square
dx = ixv - ix0;
dy = iyv - iy0;
// I let the r, g, b, a on purpose for debugging
r = inner(srcCanvasData.data[idxS00], srcCanvasData.data[idxS10], srcCanvasData.data[idxS01], srcCanvasData.data[idxS11], dx, dy);
destCanvasData.data[idxD] = r;
g = inner(srcCanvasData.data[idxS00 + 1], srcCanvasData.data[idxS10 + 1], srcCanvasData.data[idxS01 + 1], srcCanvasData.data[idxS11 + 1], dx, dy);
destCanvasData.data[idxD + 1] = g;
b = inner(srcCanvasData.data[idxS00 + 2], srcCanvasData.data[idxS10 + 2], srcCanvasData.data[idxS01 + 2], srcCanvasData.data[idxS11 + 2], dx, dy);
destCanvasData.data[idxD + 2] = b;
a = inner(srcCanvasData.data[idxS00 + 3], srcCanvasData.data[idxS10 + 3], srcCanvasData.data[idxS01 + 3], srcCanvasData.data[idxS11 + 3], dx, dy);
destCanvasData.data[idxD + 3] = a;
}
}
};
This scales an image down to a width of config.maxWidth, maintaining the original aspect ratio. At the time of development this worked on iPad/iPhone Safari in addition to major desktop browsers (IE9+, Firefox, Chrome) so I expect it will still be compatible given the broader uptake of HTML5 today. Note that the canvas.toDataURL() call takes a mime type and image quality which will allow you to control the quality and output file format (potentially different to input if you wish).
The only point this doesn't cover is maintaining the orientation information, without knowledge of this metadata the image is resized and saved as-is, losing any metadata within the image for orientation meaning that images taken on a tablet device "upside down" were rendered as such, although they would have been flipped in the device's camera viewfinder. If this is a concern, this blog post has a good guide and code examples on how to accomplish this, which I'm sure could be integrated to the above code.
Correction to above:
<img src="" id="image">
<input id="input" type="file" onchange="handleFiles()">
<script>
function handleFiles()
{
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 400;
var MAX_HEIGHT = 300;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
document.getElementById('image').src = dataurl;
}
// Load files into file reader
reader.readAsDataURL(file);
// Post the data
/*
var fd = new FormData();
fd.append("name", "some_filename.jpg");
fd.append("image", dataurl);
fd.append("info", "lah_de_dah");
*/
}</script>
Modification to the answer by Justin that works for me:
Added img.onload
Expand the POST request with a real example
function handleFiles()
{
var dataurl = null;
var filesToUpload = document.getElementById('photo').files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
img.src = e.target.result;
img.onload = function () {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
dataurl = canvas.toDataURL("image/jpeg");
// Post the data
var fd = new FormData();
fd.append("name", "some_filename.jpg");
fd.append("image", dataurl);
fd.append("info", "lah_de_dah");
$.ajax({
url: '/ajax_photo',
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
$('#form_photo')[0].reset();
location.reload();
}
});
} // img.onload
}
// Load files into file reader
reader.readAsDataURL(file);
}
If you don't want to reinvent the wheel you may try plupload.com
Typescript
async resizeImg(file: Blob): Promise<Blob> {
let img = document.createElement("img");
img.src = await new Promise<any>(resolve => {
let reader = new FileReader();
reader.onload = (e: any) => resolve(e.target.result);
reader.readAsDataURL(file);
});
await new Promise(resolve => img.onload = resolve)
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
let MAX_WIDTH = 1000;
let MAX_HEIGHT = 1000;
let width = img.naturalWidth;
let height = img.naturalHeight;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
let result = await new Promise<Blob>(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
return result;
}
The accepted answer works great, but the resize logic ignores the case in which the image is larger than the maximum in only one of the axes (for example, height > maxHeight but width <= maxWidth).
I think the following code takes care of all cases in a more straight-forward and functional way (ignore the typescript type annotations if using plain javascript):
private scaleDownSize(width: number, height: number, maxWidth: number, maxHeight: number): {width: number, height: number} {
if (width <= maxWidth && height <= maxHeight)
return { width, height };
else if (width / maxWidth > height / maxHeight)
return { width: maxWidth, height: height * maxWidth / width};
else
return { width: width * maxHeight / height, height: maxHeight };
}
fd.append("image", dataurl);
This will not work. On PHP side you can not save file with this.
Use this code instead:
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
var file = new Blob([new Uint8Array(array)], {type: 'image/png', name: "avatar.png"});
fd.append("image", file); // blob file
Resizing images in a canvas element is generally bad idea since it uses the cheapest box interpolation. The resulting image noticeable degrades in quality. I'd recommend using http://nodeca.github.io/pica/demo/ which can perform Lanczos transformation instead. The demo page above shows difference between canvas and Lanczos approaches.
It also uses web workers for resizing images in parallel. There is also WEBGL implementation.
There are some online image resizers that use pica for doing the job, like https://myimageresizer.com
You can use dropzone.js if you want to use simple and easy upload manager with resizing before upload functions.
It has builtin resize functions, but you can provide your own if you want.

Resources