How to optimize image resolution using jquery? - javascript

I'm making a chessboard UI and I am not satisfied with it's resolution so I thought of optimizing its resolution.
This is my code so far:
function optimizeResolution(element) {
var img = new Image();
var canvas = $('<canvas></canvas>')[0];
img.onload = () => {
canvas.width = '128px';
canvas.height = '128px';
canvas.getContext('2d').drawImage(element[0], 0, 0, 128, 128);
};
img.src = element.attr('src');
element.attr('src', canvas.toDataURL('image/png'));
}
The problem is that the canvas not drawing anything.

Related

Image dimensions not reflected correctly

I am trying to get the base64 of some images in Javascript and was using this function:
function getBase64Image(img) {
return new Promise((data) => {
var canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
data(canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg|jpeg);base64,/, ""))
})
}
Then I call the function to load in the image using:
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
getBase64Image(this).then(data => {})
}
img.src = wha[1][0]
If I look at the naturalWidth of the image (96px), it is different from the actual image itself (640px). I had been looking at other methods of getting base64 from an image but they also return the same results.

How can I concatenate two images in one? Without any framework, only with JS

I need some help with code review and re-translate it out of jQuery to plain JS.
I've tried to translate this into pure JS, but I don't get clearly why it doesn't work. If needed, I can show what I've made.
After the user selects an image from the first input, it should be rendered on canvas.
After the user selects an image from the second input, it should be rendered on the same canvas to the right of the first image.
Images should be rendered in scale, so two pictures will have the same height on canvas, but with the original aspect ratio.
User can select images in any order, but rendering order should stay the same: image from first input appears on canvas before image from the second input.
Inputs should accept only images.
$('.file1, .file2').on('change', function() {
var reader = new FileReader(),
imageSelector = $(this).data('image-selector');
if (this.files && this.files[0]) {
reader.onload = function(e) {
imageIsLoaded(e, imageSelector)
};
reader.readAsDataURL(this.files[0]);
}
});
$('.btn-merge').on('click', merge);
function imageIsLoaded(e, imageSelector) {
$(imageSelector).attr('src', e.target.result);
$(imageSelector).removeClass('hidden');
};
function merge() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
imageObj1 = new Image(),
imageObj2 = new Image();
imageObj1.src = $('.image1').attr('src');
imageObj1.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj1, 0, 0, 328, 526);
imageObj2.src = $('.image2').attr('src');;
imageObj2.onload = function() {
ctx.globalAlpha = 0.5;
ctx.drawImage(imageObj2, 15, 85, 300, 300);
var img = canvas.toDataURL('image/jpeg');
$('.merged-image').attr('src', img);
$('.merged-image').removeClass('hidden');
}
};
}
You should define the onload before changing source and not inside another onload
function merge() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
imageObj1 = new Image(),
imageObj2 = new Image();
imageObj1.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj1, 0, 0, 328, 526);
}
imageObj2.onload = function() {
ctx.globalAlpha = 0.5;
ctx.drawImage(imageObj2, 15, 85, 300, 300);
var img = canvas.toDataURL('image/jpeg');
$('.merged-image').attr('src', img);
$('.merged-image').removeClass('hidden');
}
imageObj1.src = $('.image1').attr('src');
imageObj2.src = $('.image2').attr('src');
}

Drawing ends up all black

I'm trying to resize an image via HTML canvas, but when I display it, it displays all black.
My code
function onSuccess(imageData) {
var img = new Image();
img.src = imageData;
window.setTimeout(function() {
var maxSize = 200;
var canvas = document.createElement("canvas");
canvas.width = maxSize;
canvas.height = maxSize;
var ctx = canvas.getContext("2d");
ctx.drawImage(img.src, 0, 0, maxSize, maxSize);
dataurl = canvas.toDataURL("image/jpeg");
alert(dataurl);
}, 1000);
}
I'm not exactly sure what it is I'm doing incorrectly. Thanks for the help!

The image convert to the canvas, and the canvas convert to the image again is impossible in Javascript? [duplicate]

This question already has answers here:
Why does canvas.toDataURL() throw a security exception?
(10 answers)
Javascript Canvas Get images pixel data
(1 answer)
Closed 9 years ago.
Can I convert an image to canvas, and vice-versa, with Javascript?
I would like to convert the image to canvas, draw something on the canvas, and then convert the canvas back to an image again.
var canvas = document.getElementById("CANVAS"),
img = new Image();
img.src = canvas.toDataURL(); //=> Error is occurred at this point.
img.onload = function(){
// ...
};
When I convert the canvas to an image, it fails.
SecurityError: The operation is insecure.
The picture is being served from a server.
Is the way wrong? Is it impossible?
The problem was resolved. Thank you for dystroy.
.htaccess
Header set Access-Control-Allow-Origin http://mysite-domain #=> The point of solution
javascript
convert the image to canvas
this.imageToCanvas = function()
{
var self = this,
img = new Image();
img.src = document.getElementById("IMAGE").src;
img.crossOrigin = "anonymous"; //=> The point of solution
img.onload = function(){
var canvas = document.getElementById("CANVAS");
if ( ! canvas || ! canvas.getContext ) { return false; }
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
self.draw();
};
};
draw something on the canvas
this.draw = function()
{
var self = this,
text = "stackoverflow",
img = new Image();
img.crossOrigin = "anonymous"; //=> The point of solution
img.src = document.getElementById("SECOND-IMAGE").src;
img.onload = function(){
var canvas = document.getElementById("CANVAS");
if ( ! canvas || ! canvas.getContext ) { return false; }
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 10, 10, img.width, img.height);
ctx.save();
ctx.font = "italic bold 32px 'Times New Roman'";;
ctx.fillStyle = "#0067ef";
ctx.fillText(text, 50, 50);
ctx.restore();
self.canvasToImage(canvas);
};
};
convert the canvas back to an image again
this.canvasToImage = function(_canvas)
{
var img = new Image();
img.id = "IMAGE";
img.src = _canvas.toDataURL(); //=> It succeeds this time.
$("#" + _canvas.id).replaceWith(img); //=> with jQuery
};

Javascript FileReader eats up all the memory when reads local images

I'm working on a concent to show the thumbnail of a large number of images from the local drive.
With HTML5 File API is seems quite possible, but whn I try to load a big number of images the memory usage of the browser goes over the roof and the collapses.
I think the problem is that the FileReader doesn't releases the memory after a file read.
Originally I had a new instance of FileReader and a simple loop to iterate through the images.
To solve this memory problem I replaced this to have one FileReader only, but it did not really help.
Here is the relevand code block:
<script>
var areader = new FileReader();
var counter=0;
function loadImage(file) {
var canvas = document.createElement("canvas");
areader.onload = function (event) {
var img = new Image;
img.onload = function () {
canvas.width = img.width / 100;
canvas.height = img.height / 100;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width / 100, img.height / 100);
var browse = document.getElementById("uploadInput");
if (browse.files.length > counter) {
counter++;
areader.result = null;//I don't think this makes any difference
loadImage(browse.files[counter]);
}
};
img.src = event.target.result;
};
areader.readAsDataURL(file);
preview.appendChild(canvas);
}
function showImages() {
loadImage(document.getElementById("uploadInput").files[0]);
}
If anybody come across this problem the I do something very stupid could you reply.
Thanks,
Tamas
It's not the file reader but you are using the entire image's data in base64 as the src property of the image, which will actually take 133% of the image's size in memory.
You should use Blob URLs instead:
var URL = window.URL || window.webkitURL;
function loadImage( file ) {
var canvas = document.createElement("canvas"),
img = new Image();
img.onload = function() {
canvas.width = img.width / 100;
canvas.height = img.height / 100;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width / 100, img.height / 100);
URL.revokeObjectURL( img.src );
img = null;
var browse = document.getElementById("uploadInput");
if (browse.files.length > counter) {
counter++;
loadImage(browse.files[counter]);
}
};
img.src = URL.createObjectURL( file );
preview.appendChild(canvas);
}

Categories