I am using compressor.js for image compression and watermarking. However, only text based watermark seems to be possible to me. I want to add image (logo) into watermark too.
Any idea how to use image as watermark with compressor.js?
You can do this by using the drew function, like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.0.7/compressor.min.js"></script>
</head>
<body>
<img id="watermark" src="watermark.png" style="display: none" />
<h3>Input</h3>
<div id="input"><img id="image" src="picture.png" style="max-width:250px"></div>
<h3>Output</h3>
<div id="output"></div>
<script>
window.addEventListener('DOMContentLoaded', function () {
var Compressor = window.Compressor;
var URL = window.URL || window.webkitURL;
var image = document.getElementById('image');
var output = document.getElementById('output');
var watermark = document.getElementById('watermark');
var xhr = new XMLHttpRequest();
xhr.onload = function () {
new Compressor(xhr.response, {
strict: false,
drew: function (context, canvas) {
context.drawImage(
watermark,
0,
0,
watermark.width,
watermark.height,
canvas.width - ((watermark.width / 4) + 10),
canvas.height - ((watermark.height / 4) + 10),
(watermark.width / 4),
(watermark.height / 4))
},
success: function (result) {
var newImage = new Image();
newImage.src = URL.createObjectURL(result);
newImage.style = "max-width:250px";
output.appendChild(newImage);
},
error: function (err) {
window.alert(err.message);
},
});
};
xhr.open('GET', image.src);
xhr.responseType = 'blob';
xhr.send();
});
</script>
</body>
</html>
All of the dividing by 4 is because my watermark image is massive. That's not required.
Here's a screenshot of the before/after:
Alternative Method
Here's an alternative way to add a watermark to an image:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<img id="watermark" src="https://upload.wikimedia.org/wikipedia/en/7/71/Corona_Extra.svg" style="display: none" />
<img id="image" src="https://images.unsplash.com/photo-1665606855702-144fd49af552?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80%20870w" style="display:none">
<canvas id="output"></canvas>
<script>
var imagesLoaded = 0;
var main = document.getElementById("image");
var watermark = document.getElementById("watermark");
function imageHasLoaded() {
imagesLoaded++;
if (imagesLoaded == 2) {
var c = document.getElementById("output");
var ctx = c.getContext("2d");
c.width = main.width;
c.height = main.height;
ctx.drawImage(main,
0, 0,
main.width, main.height,
0, 0,
main.width, main.height);
ctx.drawImage(watermark,
0, 0,
watermark.width, watermark.height,
(main.width - watermark.width) / 2, (main.height - watermark.height),
watermark.width, watermark.height);
}
}
main.load = imageHasLoaded();
watermark.load = imageHasLoaded();
</script>
</body>
</html>
Related
I want to create a function which compress the image after selecting and append it to the body.
Here is my code =>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Image Compression</title>
</head>
<body>
<input type="file" accept=".jpg,.jpeg,.png" id="random-img" />
</body>
<script>
const Compress = function (img_obj, quality, output_format) {
var mime_type = output_format;
var cvs = document.createElement("canvas");
img_obj.onload = function () {
cvs.width = img_obj.naturalWidth;
cvs.height = img_obj.naturalHeight;
};
var ctx = cvs.getContext("2d").drawImage(img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality / 100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
};
function getImg() {
const src_obj = document.getElementById("random-img").files[0];
const newImg = new Image();
newImg.src = URL.createObjectURL(src_obj);
const compressed_img = Compress(newImg, 80, src_obj.type);
document.querySelector("body").appendChild(compressed_img);
}
document.querySelector("input").addEventListener("change", getImg);
</script>
</html>
The problem is I am not able to see the image on the screen.Instead I see any empty white box of 300 x 150 size when I open the developer tool and hover over the image element.
Please help! Thankyou!
img_obj.onload() is asynchronous, you can't just immediately return from it.
const Compress = function (img_obj, quality, output_format) {
var mime_type = output_format;
var cvs = document.createElement("canvas");
img_obj.onload = function () {
cvs.width = img_obj.naturalWidth;
cvs.height = img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality / 100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
document.querySelector("body").appendChild(result_image_obj);
};
};
function getImg() {
const src_obj = document.getElementById("random-img").files[0];
const newImg = new Image();
newImg.src = URL.createObjectURL(src_obj);
const compressed_img = Compress(newImg, 80, src_obj.type);
}
document.querySelector("input").addEventListener("change", getImg);
<input type="file" accept=".jpg,.jpeg,.png" id="random-img" />
i wrote this code but the browser refuse to display the pipe image from canvas. I need some help please.
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
var chickenImage = new Image();
var pipe = new Image();
var jumpSound = new Audio();
chickenImage.src="asset/chicken.png";
pipe.src ="asset/pipe.png";
jumpSound.src ="asset/jump.wav";
function draw(){
ctx.drawImage(pipe,100,0);
}
draw();
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>chicken</title>
</head>
<body>
<canvas id="canvas" width="288" height="512"></canvas>
<script src="main.js"></script>
</body>
</html>
You will need to wait for onload event, for the image to be loaded then you can draw her in the canvas.
pipe.onload = function () {
ctx.drawImage(pipe, 0, 0);
};
pipe.src ="asset/pipe.png";
Or in your code you can use also:
pipe.onload = function () {
draw();
};
pipe.src ="asset/pipe.png";
You need to wait until the image is loaded. The easiest way would be the .onload event which is run, when the image is finished loading and to use it just set it to your draw() function.
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
var chickenImage = new Image();
var pipe = new Image();
var jumpSound = new Audio();
//chickenImage.src="asset/chicken.png";
pipe.src = "https://lorempixel.com/g/400/200/?random";
//jumpSound.src ="asset/jump.wav";
function draw() {
ctx.drawImage(pipe, 100, 0);
}
pipe.onload = draw;
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>chicken</title>
</head>
<body>
<canvas id="canvas" width="288" height="512"></canvas>
</body>
</html>
My idea is to grab an image from an URL, send it through a cors proxy, convert that to base64, then remove the white space from the image and replace that with a transparent background. I have managed to do that:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Image</title>
<style>
body {
background: darkslategrey;
}
.text {
color: white;
}
</style>
</head>
<body>
<!-- Original -->
<h3 class="text">Original</h3>
<img src="" id="original">
<!-- Modified -->
<h3 class="text">Modified</h3>
<canvas id="modified"></canvas>
<script src="../CommonLinkedFiles/jquery3_2_1.js"></script>
<script>
var stockSymbol = "extr";
var logoUrl = "https://storage.googleapis.com/iex/api/logos/" + stockSymbol.toUpperCase() + ".png";
// Converting URL to Base64 with the use of a proxy
var getDataUri = function (targetUrl, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
var proxyUrl = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyUrl + targetUrl);
xhr.responseType = 'blob';
xhr.send();
};
// Returns Base 64 of image
getDataUri(logoUrl, function (base64) {
console.log('RESULT:', base64);
//original
$("#original").attr("src", base64);
var canvas = document.getElementById("modified"),
ctx = canvas.getContext("2d"),
image = document.getElementById("original");
canvas.height = canvas.width = 128;
ctx.drawImage(image,0,0);
var imgd = ctx.getImageData(0, 0, 128, 128),
pix = imgd.data,
newColor = {r:0,g:0,b:0, a:0};
for (var i = 0, n = pix.length; i <n; i += 4) {
var r = pix[i],
g = pix[i+1],
b = pix[i+2];
if(r == 255&& g == 255 && b == 255){
// Change the white to the new color.
pix[i] = newColor.r;
pix[i+1] = newColor.g;
pix[i+2] = newColor.b;
pix[i+3] = newColor.a;
}
}
ctx.putImageData(imgd, 0, 0);
});
</script>
</body>
You can see here at: JsFiddle
My question is how do I remove all of the white space given any image.
Edit: Keith Solved the image by adding on onload function.
After some tinkering, I figured out that all of the "white" pixels were not exactly white so I so modifying the if statement it searched for all of near white pixels:if(r >= 250&& g >= 250 && b >= 250){
JSFiddle
I am trying to get image from external link and add in a document.
Html service work fine. However, document should fill out after onload function.
How can I fix it ?
code.gs
function doGet(e){
var content = HtmlService.createHtmlOutputFromFile('index').getContent();
return HtmlService.createHtmlOutput(content);
}
function im(baseUrl){
var resp = UrlFetchApp.fetch(baseUrl);
var docID = "0000xxxxx1111"
var doc = DocumentApp.openById(docID);
doc.getChild(0).asParagraph().appendInlineImage(resp.getBlob());
return baseUrl;
}
index.html
<!DOCTYPE html>
<head>
<base target="_top">
<script>
window.onload = function() {
var url = "http://xxx.co/image.png"
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
document.getElementById('barcode').appendChild(canvas);
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = url;
ctx.drawImage(image, 0, 0);
google.script.run.withSuccessHandler(function(a) {
document.getElementById("imageid").src=a;
}).im(canvas.toDataURL());
}
</script>
</head>
<body>
<img id="imageid" src="" alt="image">
</body>
</html>
There are a few problems with your HTML which is why it probably isn't working. You also had not tagged any elements with the barcode id.
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body id="barcode">
<img id="imageid" src="" alt="image">
</body>
<script>
window.onload = function() {
var url = "http://lorempixel.com/400/200/"
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
document.getElementById('barcode').appendChild(canvas);
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = url;
ctx.drawImage(image, 0, 0);
google.script.run.withSuccessHandler(function(a) {
document.getElementById("imageid").src=a;
}).im(canvas.toDataURL());
}
</script>
</html>
I'm completely new to javascript but not to programming...for the life of me I cannot figure this out. I'm trying to draw an image on a canvas. I can get a rectangle to draw but not an image.
Here's my code:
<head>
<meta http-equiv = "Content-type" content = "text/html;charset=utf-8">
<meta name = "viewport" id = "viewport" content = "width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;"/>
<script type = "text/javascript">
function drawPic()
{
////////////// DOESN'T WORK ///////////////////
var canvas = document.getElementById('mainCanvas');
if (canvas.getContext)
{
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function ()
{
canvas.drawImage(img, 0, 0);
};
img.src = "pic1.jpg";
}
///////////////////////////////////////////////////////////////
///////////// WORKS //////////////////////////////////////////
if (canvas.getContext)
{
var context = canvas.getContext('2d');
context.fillStyle = "rgb(150,29,28)";
context.fillRect(2, 2, 96, 96);
}
}
</script>
</head>
<body onload = "drawPic();">
<canvas id = "mainCanvas"></canvas>
</body>
well instead of canvas.drawImage(img, 0, 0); it should be called on context - context.drawImage(img, 0, 0); . Hope it helps :)
You need to make an AJAX Call.
Add something like this to your code and the image should load:
window.onload = function() {
// make ajax call to get image data url
var request = new XMLHttpRequest();
request.open("GET", "http://www.html5canvastutorials.com/demos/assets/dataURL.txt", true);
request.onreadystatechange = function() {
// Makes sure the document is ready to parse.
if(request.readyState == 4) {
// Makes sure it's found the file.
if(request.status == 200) {
loadCanvas(request.responseText);
}
}
};
request.send(null);
};
See this tutorial for a full example: http://www.html5canvastutorials.com/advanced/html5-canvas-load-image-data-url/