JavaScript array to PNG? - client side - javascript

Is there any way converting a 2d array of hex codes to a png image?
The arrays look like this (only much larger)
[
[
'#FF0000',
'#00FF00'
],
[
'#0000FF',
'#000000'
]
]
From this array, the image should look like this
If the method doesn't work with arrays like this, what type of array will it work with?

If you want to render a PNG client-side, without libraries, you can use the HTML5 Canvas.
Either way, I recommend to stick to a one-dimension array, and store the image’s dimensions. It makes things a lot easier to work with.
var pixels = [ ... ], // your massive array
width = 4, // width in pixels
height = Math.ceil(pixels.length / width),
// Create canvas
canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
imgData = context.createImageData(width, height);
canvas.height = height;
canvas.width = width;
// fill imgData with colors from array
for(var i = 0; i < pixels.length; i++) {
// Convert pixels[i] to RGB
// See http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
imgData[i] = r;
imgData[i + 1] = g;
imgData[i + 2] = b;
imgData[i + 3] = 255; // Alpha channel
}
// put data to context at (0, 0)
context.putImageData(imgData, 0, 0);
// output image
var img = new Image();
img.src = canvas.toDataURL('image/png');
// add image to body (or whatever you want to do)
document.body.appendChild(img);
Alternatively, if you can’t rely on a relatively new feature like this, or simply find this too much work, you can go for Tom’s answer :)

PNGlib looks helpful. You would have to create a loop similar to their example:
var p = new PNGlib(200, 200, 256);
for (var x = 0; x < 2; x++)
for (var y = 0; y < 2; y++)
p.buffer[p.index(x, y)] = p.color(/* your colour */);
document.write('<img src="data:image/png;base64,' + p.getBase64() + '">');
It's difficult to give a more specific example with the information that you've provided, but I think that this is what you're after. You would obviously have to change the x and y limits for different arrays.

You could draw the array of RGB values to a HTML5 canvas object and then get the contents of that canvas using the .toDataURL() canvas method:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
"use strict";
// Here's the image data we want to draw:
var data = [
["#FF0000", "#00FF00"],
["#FFFF00", "#0000FF"]
];
// First, we need to create a canvas with the same dimensions as the image data:
var canvas = document.createElement("canvas");
canvas.height = data.length;
canvas.width = data[0].length;
//canvas.style.visibility = "hidden";
document.body.appendChild(canvas);
// Now that we have canvas to work with, we need to draw the image data into it:
var ctx = canvas.getContext("2d");
for (var y = 0; y < data.length; ++y) {
for (var x = 0; x < data[y].length; ++x) {
ctx.fillStyle = data[y][x];
ctx.fillRect(x, y, 1, 1);
}
}
// Finally, we get the image data using the .toDataURL() canvas method:
console.log(canvas.toDataURL("image/png"));
</script>
</body>
</html>

Solution for the image stored in 2 dimensional array, with RGB colors
as an answer to another question
var img=[[[0,0,0],[0,0,0],[0,0,0],[255,0,0],[0,0,0]],
[[0,0,0],[0,0,255],[0,0,0],[0,0,0],[255,0,0]],
[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[255,0,0]],
[[0,0,0],[0,0,255],[0,0,0],[0,0,0],[255,0,0]],
[[0,0,0],[0,0,0],[0,0,0],[255,0,0],[0,0,0]]];
var pixelSize = 20;
var c = document.createElement("canvas");
c.height = img[0].length * pixelSize;
c.width = img.length * pixelSize;
document.body.appendChild(c);
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
for (var i = 0; i < img.length; i++) {
for (var j = 0; j < img[0].length; j++) {
ctx.fillStyle = "rgb("+img[i][j][0]+","+img[i][j][1]+","+img[i][j][2]+")";
ctx.fillRect(i*pixelSize, j*pixelSize, pixelSize, pixelSize);
}
}
console.log(c.toDataURL("image/png"));
var png = document.createElement("img");
png.src = c.toDataURL("image/png");
c.remove();
document.body.appendChild(png);

Or use an updated version of pnglib:
https://github.com/IjzerenHein/pnglib-es6

Related

Error displaying an image from localhost on p5js Canvas

Problem:
I am learning p5.js and I am following a tutorial from Coding Train YouTube channel. Everything was fine until I had to call a library function on an Image object. The problem is that I have instantiated the library in an object p and I'm using it's variables through p object. I don't know why it isn't recognizing the loadPixels() function. In the tutorial, the function works fine.
Error Message:
🌸 p5.js says: There's an error as "loadPixels" could not be called as a function
(on line 17 in help.html [file:///G:/Android/help.html:17:11]).
Verify whether "img" has "loadPixels" in it and check the spelling, letter-casing (Javacript is case-sensitive) and its type.
For more: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/Not_a_function#What_went_wrong
Code:
<!DOCTYPE html>
<head>
<script src='p5/p5.js'></script>
</head>
<body>
<div id='container'></div>
<script>
let sketch = function(p) {
p.setup = function(){
p.createCanvas(56, 56);
img = new Image();
img.src = "scott.jpg";
}
p.draw = function() {
// p.drawingContext.drawImage(img, 0, 0);
p.loadPixels();
img.loadPixels();
for (var x=0; x<p.width; x++) {
for (var y=0; y<p.height; y++) {
// var d = p.dist(x, y, p.width/2, p.height/2);
var loc = x+y+p.width;
// p.pixels[loc] = p.color(d);
p.pixels[loc] = img.pixels[loc];
}
}
}
p.updatePixels();
};
new p5(sketch, 'container');
</script>
</body>
</html>
Edit:
As someone pointed out that the problem is that I'm using Image() which is the default Image class for javascript. I did some changes to my code but now it gives me this error.
Error :-
Uncaught DOMException: The operation is insecure. help.html:18
openWindow file:///G:/Android/help.html:18
onclick file:///G:/Android/help.html:1
Code :-
<!DOCTYPE html>
<head>
<script src='p5/p5.js'></script>
</head>
<body>
<button onclick="openWindow()">click me to open a new window.</button>
<div id='container'></div>
<script>
function openWindow() {
var newWindow = window.open("", "Import Image", "height=56,width=56,status=yes,toolbar=no,menubar=no,location=no");
newWindow.document.write("<canvas id='imagePlaceholder'>Canvas not supported!</canvas>");
var canvas = newWindow.document.getElementById("imagePlaceholder");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// console.log(ctx.getImageData(0, 0, 56, 56).data);
dest = ctx.getImageData(0, 0, 56, 56).data;
}
let sketch = function(p) {
p.setup = function(){
p.createCanvas(56, 56);
img = new Image();
img.src = "scott.jpg";
let dest = p.createImage(56, 56);
console.log(img);
}
p.draw = function() {
// p.drawingContext.drawImage(img, 0, 0);
// p.loadPixels();
img.loadPixels();
for (var x=0; x<p.width; x++) {
for (var y=0; y<p.height; y++) {
// var d = p.dist(x, y, p.width/2, p.height/2);
var loc = x+y+p.width;
// p.pixels[loc] = p.color(d);
p.pixels[loc] = img.pixels[loc];
}
}
}
p.updatePixels();
};
new p5(sketch, 'container');
</script>
</body>
</html>
Because you are specifically trying to load an image from a local computer as opposed to a publicly accessible URL, a file input with user interaction is going to be the only way to do this. This is a deliberate constraint put in place by web browsers to prevent a malicious webpage from illicitly reading data from your local files. However there is a much simpler way to get the image data from the file input onto your p5js canvas. In fact this exact use case can be seen in the documentation for the createFileInput function.
let input;
let img;
function setup() {
input = createFileInput(handleFile);
input.position(0, 0);
}
function draw() {
background(255);
if (img) {
image(img, 0, 0, width, height);
}
}
function handleFile(file) {
if (file.type === 'image') {
img = createImg(file.data, '');
img.hide();
} else {
img = null;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
</head>
<body>
</body>
</html>
One obvious problem here is that you are using the builtin Image() constructor, which creates an HTMLImageTag (see the MDN Article) instead of creating a p5js p5.Image object (see the p5js Reference). However there are several other issues. In p5js you need to load images in the preload function to ensure they are available when you start drawing (this is an asynchronous operation). You'd have a much easier time drawing images in p5js using the built in image function. If you are going to use pixel arrays, you need to understand the structure of these arrays. They don't store Color objects, they store 4 separate numbers for each color channel (red, green, blue, and alpha). So the indices in the array are not (x + y * width), but ((x + y * width) * 4 + channel) where channel is a number from 0 to 3. Also you need to account for the fact that the canvas may have a pixel density > 1, whereas the image will have a pixel density of 1. I strongly suggest you read all of the documentation for the Image related p5js functions.
let sketch = function(p) {
let img;
p.preload = function() {
img = p.loadImage("https://s3-ap-southeast-1.amazonaws.com/investingnote-production-webbucket/attachments/41645da792aef1c5054c33de240a52e2c32d205e.png");
};
p.setup = function() {
p.createCanvas(200, 200);
};
p.draw = function() {
// this would be a lot simpler way to draw the image:
// p.image(img, 0, 0);
p.loadPixels();
img.loadPixels();
// Handle high pixel density displays. This code effectively scale the image up so that each 1 pixel in the source image is density * density pixels in the display, thus preserving the size of the image but leading to visible pixelation.
let density = p.pixelDensity();
for (var x = 0; x < p.width && x < img.width; x++) {
for (var y = 0; y < p.height && y < img.height; y++) {
// There are 4 values per pixel in the pixels array:
var srcLoc = (x + y * img.width) * 4;
for (var xd = 0; xd < density; xd++) {
for (var yd = 0; yd < density; yd++) {
var destLoc =
(x * density + xd + (y * density + yd) * p.width * density) * 4;
for (var i = 0; i < 4; i++) {
p.pixels[destLoc + i] = img.pixels[srcLoc + i];
}
}
}
}
}
p.updatePixels();
};
};
new p5(sketch, 'container');
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
</head>
<body>
<div id='container'></div>
</body>
</html>
Here is an alternate version of the snippet that handles pixelDensity differently:
let sketch = function(p) {
let img;
p.preload = function() {
img = p.loadImage("https://s3-ap-southeast-1.amazonaws.com/investingnote-production-webbucket/attachments/41645da792aef1c5054c33de240a52e2c32d205e.png");
};
p.setup = function() {
p.createCanvas(200, 200);
};
p.draw = function() {
// this would be a lot simpler way to draw the image:
// p.image(img, 0, 0);
p.loadPixels();
img.loadPixels();
// Handle high pixel density displays. This code shrinks the image down by mapping one pixel in the source image to 1 / (density ^ 2) actual pixels in the canvas.
let density = p.pixelDensity();
for (var x = 0; x < p.width * density && x < img.width; x++) {
for (var y = 0; y < p.height * density && y < img.height; y++) {
// There are 4 values per pixel in the pixels array:
var srcLoc = (x + y * img.width) * 4;
var destLoc = (x + y * p.width * density) * 4;
for (var i = 0; i < 4; i++) {
p.pixels[destLoc + i] = img.pixels[srcLoc + i];
}
}
}
p.updatePixels();
};
};
new p5(sketch, 'container');
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
</head>
<body>
<div id='container'></div>
</body>
</html>
I tried a lot of things and almost giveup, but at the end I had to change the code a bit and this worked for me. Although what I got was base64 url as Alice in the comment suggested and I converted it into Uint8ClampedArray. Now if anyone wants a full image or all the pixels of an image then they can follow this link :- https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas . I hope it will be helpful for anyone who wants to make an offline webcanvas based application and don't want to dabble with CORS.
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.setAttribute('accept', 'image/gif, image/jpeg, image/png');
fileSelector.click();
fileSelector.onchange = function(e) {
img = new Image();
var file = e.target.files[0];
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
var newWindow = window.open("", "_blank", "height=56,width=56,status=yes,toolbar=no,menubar=no,location=no");
newWindow.document.write("<canvas id='imagePlaceholder'>Canvas not supported!</canvas>");
var canvas = newWindow.document.getElementById("imagePlaceholder");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// console.log(ctx.getImageData(0, 0, 56, 56).data);
var dest = ctx.getImageData(0, 0, img.width, img.height).data;
console.log(dest);
newWindow.close();
}

Dynamically changing Text color depending on Background Image

right now I am writing a small chrome extension. the extension grabs the Bing Image of the Day and sets it as the body background image, and then the extension also grabs the weather, time, date, etc. The problem is that sometimes the image of the day is for example, bright on one side and dark on the other. So, no matter what color the text is, some of it is illegible. How can I determine what color each text should be depending on the background image color behind a SPECIFIC text?
Thanks in advance.
You can use jQuery's attr() function. For example, if you img tag has an id attribute of 'my_image':
<img id="my_image" src="first.jpg"/>
Jquery
$("#my_image").attr("src","second.jpg");
I got something to work.... It is kind of makeshift and not foolproof, but I found a script that calculates overall brightness, which then allows the script to decide whether it should display black or white text. Seems to work well, as of now. Here it is:
function getImageBrightness(imageSrc) {
var img = document.createElement("img");
img.src = imageSrc;
img.style.display = "none";
document.body.appendChild(img);
var colorSum = 0;
img.onload = function () {
// create canvas
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
var r, g, b, avg;
for (var x = 0, len = data.length; x < len; x += 4) {
r = data[x];
g = data[x + 1];
b = data[x + 2];
avg = Math.floor((r + g + b) / 3);
colorSum += avg;
}
brightness = Math.floor(colorSum / (this.width * this.height));
console.log(brightness);
if (brightness < 150) {
$(".contrast").css("color", "white");
} else {
$(".contrast").css("color", "black");
}
}
}
credit to: https://jsfiddle.net/s7Wx2/

How can i save an image in my computer that has been filtered with CSS [duplicate]

I'm building a new website that will let users apply filters to images (just like Instagram). I will use -webkit-filter for that.
The user must be able to save the filtered image. There is any way I can do that using JavaScript?
You can't save images directly, but you can render them in Canvas, then save from there.
See: Save HTML5 canvas with images as an image
There is no direct/straight forward method to export an image with CSS Filter.
Follow the below steps for Saving/Exporting an Image with -webkit-filter applied on it:
1. Render the image to a canvas:
var canvas = document.createElement('canvas');
canvas.id="canvasPhoto";
canvas.width = imageContaainer.width;
canvas.height = imageContaainer.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(imageContaainer, 0, 0, canvas.width, canvas.height);
Get the ImageData from canvas and apply the filter. Eg: I will apply grayscale filter to the ImageData below:
function grayscale(ctx) {
var pixels = ctx.getImageData(0,0,canvas.width, canvas.height);
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
var v = 0.2126*r + 0.7152*g + 0.0722*b;
d[i] = d[i+1] = d[i+2] = v
}
context.putImageData(pixels, 0, 0);
}
Add an event and use the below code to trigger download
function download(canvas) {
var data = canvas.toDataURL("image/png");
if (!window.open(data))
{
document.location.href = data;
}
}

How to change window level of an image on canvas using javascript

I have an image on canvas or a set of images that i draw on the canvas. I can draw them fine but I want to change the window level of the image on canvas by dragging the mouse over it. I've seen a lot of external javascript api's but they're quite huge and i don't want to use them for this purpose.
here's my JSFIDDLE that is basically drawing an image on the canvas
this is how my code looks
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
ctx.drawImage(img, 0, 0);
}
// Specify the src to load the image
img.src = "http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample5_l.jpg";
i need something with basic JS or JQuery. it would be great if you can point me in the right direction using a sample code.
Thanks in advance.
If you want to use JavaScript, try something like:
<script>
var c = document.getElementById("drawingboard");
var ctx = c.getContext("2d");
var mouseDown = 0;
document.body.ontouchstart = function() {
mouseDown+=1;
}
document.body.ontouchend = function() {
mouseDown-=1;
}
function draw(event){
ctx.color='gold';
ctx.fillStyle = "lime";
ctx.drawImage(img,event.clientX,event.clientY);}
</script>
This is what I gained after some research:
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const rangeMin = level - window / 2;
const rangeMax = level + window / 2;
const totalSize = canvas.width * canvas.height;
for (let idx = 0; idx < totalSize; idx++) {
if (imageData.data[idx] < rangeMin) {
imageData.data[idx] = 0;
} else if (imageData.data[idx] > rangeMax) {
imageData.data[idx] = 255;
}
}
ctx.putImageData(imageData, 0, 0);

JavaScript/HTML5 Canvas - Load array of images

I have a folder of images, altogether 32x32 tiles. I am trying to load these images using JavaScript, onto an HTML5 canvas.
Here's what I have:
window.onload = function(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
var tiles = [];
canvas.width = 512;
canvas.height = 352;
for (x = 0; x <= 520; x++) {
imageObj.src = "line_tile/t"+x+".png";
tiles.push(imageObj);
}
var theX;
var theY;
for (x = 0; x <= 10; x++) {
for (y = 0; y <= 15; y++) {
theX = x*32;
theY = y*32;
context.drawImage(tiles[2], theY, theX,32,32);
console.log("Tile X: "+x+" | Tile Y: "+y+" - X Pos: "+theX+" | Y Pos: "+theY);
}
}
};
The problem is that this code only loads up the last tile (in this case tile[520]). In reality I want to load all the tiles. No matter what. How do I properely put a set of images into an array and load it?
Your modifying a single instance of imageObj; so basically you end up with an array all pointing to the same instance, which ends with 520.
try
for (x = 0; x <= 520; x++) {
var imageObj = new Image(); // new instance for each image
imageObj.src = "line_tile/t"+x+".png";
tiles.push(imageObj);
}
Not strictly related to your problem but you might encounter it (with current code)
I'm not sure if you do not need first to see if the Image was actually loaded before adding it to the tiles array.

Categories

Resources