Can i change image format? i want save as jpg, not png.
var canvas = document.getElementById("canvas_final");
var ctx = canvas.getContext("2d");
var img1 = loadImage(imageData, main);
var img2 = loadImage('imagens/mask.png', main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if(imagesLoaded == 2) {
ctx.drawImage(img1, 0, 0);
//ctx.globalAlpha = 0.5;
ctx.drawImage(img2, 0, 400);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
After display using img.src i want change file format to (jpeg) and not (png)
You can convert the canvas to a Data URI using HTMLCanvasElement.toDataURL. Depending on your requirement, you could have an export button that would request the following:
ctx.toDataURL("image/jpeg");
Related
I would like to combine two images (one uploaded from the device and another from the website) and export them as one image. The image uploaded from the device would be the background image and the one from the website is a logo to make in to a watermark in the bottom corner.
Is this possible and if so where should I start?
Thank you
I have been able to add an image on top of another image using the Javascript code below:
function watermarkLogo(elemImage) {
var canvas = document.getElementById("canvas");
canvas.width = elemImage.naturalWidth;
canvas.height = elemImage.naturalHeight;
var myVar = canvas.getContext("2d");
var img1 = loadImage(elemImage.src, myFunction);
var img2 = loadImage('icon.png', myFunction);
var numberOfImages = 0;
function myFunction() {
numberOfImages += 1;
if(numberOfImages == 2) {
myVar.drawImage(img1, 0, 0);
myVar.globalAlpha = 0.5;
var widthOffset = (canvas.width/3)*2;
var heightOffset = (canvas.height/3)*2;
myVar.drawImage(img2, widthOffset-50, heightOffset-50, 100, 100);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
}
I am convertin image to base64 string using following code
function getBase64Image() {
p = document.getElementById("fileUpload").value;
img1.setAttribute('src', p);
canvas.width = img1.width;
canvas.height = img1.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var dataURL = canvas.toDataURL("image/jpg");
$("#b64").val(dataURL);
}
But what I am getting in dataURL is Data; and there is not base64 string contained.
How can I fetch base64 string from image?
i think this could work if you use load callback because the loading is async. not sure what your fileUpload is tho, but if's a text field pasting a url
function getBase64Image() {
p = document.getElementById("fileUpload").value;
img1.setAttribute('src', p);
img1.setAttribute('load', fileLoaded);
function fileLoaded(e) {
canvas.width = img1.width;
canvas.height = img1.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var dataURL = canvas.toDataURL("image/jpeg");
$("#b64").val(dataURL);
}
}
the image type is also image/jpeg. jpg won't work or, it will return png instead since it isn't valid. and cross-origin can be a problem iirc.
Here's a simple example:
// assuming that you have jQuery lib
$('#fileUpload').on('change', function(e) {
if (this.files.length === 0) return;
var imageFile = this.files[0];
var reader = new FileReader();
// when reading of image file completes
reader.onloadend = function() {
var tempImg = new Image();
tempImg.src = reader.result;
// when image is loaded
tempImg.onload = function() {
canvas.getContext("2d").drawImage(tempImg, 0, 0);
}
}
// start reading
reader.readAsDataURL(imageFile);
});
Hope this helps!!
I would like to be able to add image filters to an image that the user uploads locally. The local upload works fine but the image is not converted to grayscale. Here is my code:
$("#file_input").change(function (e) {
var URL = window.webkitURL || window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img = new Image();
img.src = url;
img.onload = function () {
ctx = document.getElementById('myCanvas').getContext("2d");
///
fabric.Image.fromURL( img.src, function( img ) {
// add filter
img.filters.push(new fabric.Image.filters.Grayscale());
// apply filters and re-render canvas when done
img.applyFilters(ctx.renderAll.bind(ctx));
// add image onto canvas
ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
});
}
///
});
i don't understand your code.but i think you want something like this..
$("#file_input").change(function (e) {
var URL = window.webkitURL || window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img = new Image();
img.src = url;
img.onload = function () {
var canvas = new fabric.Canvas("c");
///
fabric.Image.fromURL( img.src, function( img ) {
// add filter
img.filters.push(new fabric.Image.filters.Grayscale());
// apply filters and re-render canvas when done
img.applyFilters(canvas.renderAll.bind(canvas));
// add image onto canvas
img.width = canvas.width;
img.height = canvas.height;
canvas.add(img);
});
}
///
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="file" id="file_input"/>
<canvas id="c"></canvas>
I am working on VS2015 cordova app .I want to send an base 64 string of an image to another server . I have a problem when i get image from gallery and corverting it into base64string . I got the base64string successfully but when i dispalayed it I always get black image . here is my code :
function onPhotoURISuccess(imageURI) {
var largeImage = document.getElementById('smallImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
basestrg = encodeImageUri(imageURI);
}
function getPhoto(source) {
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
destinationType: Camera.DestinationType.NATIVE_URI, mediaType: Camera.MediaType.Photo,
sourceType: source
});
}
function encodeImageUri(imageUri) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function () {
c.width = this.width;
c.height = this.height;
ctx.drawImage(img, 0, 0);
};
img.src = imageUri;
var dataURL = c.toDataURL("image/jpeg");
return dataURL;
}
Please advice .
This is beside the context but may help you.
You can upload the image directly from your html5 form.
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="userImage" type="file" accept="image/*;capture=camera">
<button type="submit">Submit</button>
</form>
Get the image data in upload.php file and save as image. In PHP use $_FILES array and for C# use HttpContext to save the image.Ref: Using form input to access camera and immediately upload photos using web app
Your image isn't loaded by the time you try to get the data url.
function encodeImageUri(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function () {
c.width = this.width;
c.height = this.height;
ctx.drawImage(img, 0, 0);
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
};
img.src = imageUri;
}
Then change the other function to pass a callback
function onPhotoURISuccess(imageURI) {
var largeImage = document.getElementById('smallImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
encodeImageUri(imageURI, function(datauri){
basestrg = datauri;
//Now send the string to the server here.
});
}
I want to resize (as in reduce the filesize if it exceeds limit) an Image using canvas. I see that the resultant image size drawn on canvas, keeping the width and height constant, results in different file size depending upon what has been drawn on canvas.
I am willing to reduce the resolution further provided I get the desired file size.
How do I make sure whatever the resolution I get file(image) size within the limit?
Refer to this fiddle
var el = document.getElementById('f');
el.addEventListener('change', onChange);
function onChange(e) {
var file = this.files[0];
console.log("CHANGING");
var fr = new FileReader();
fr.onload = function(e) {
drawOnCanvas(e.target.result);
}
fr.readAsDataURL(file);
}
function drawOnCanvas(imgSrc) {
var canv = document.createElement('canvas'),
img = new Image();
console.log("DRAWING");
canv.width = canv.height = 500;
ctx = canv.getContext('2d');
img.onload = function() {
console.log("IMAGE LOADED");
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canv.width, canv.height);
try {
document.body.removeChild(document.querySelector('canvas'));
} catch (e) {}
document.body.appendChild(canv);
blob = canvasToFile(canv.toDataURL());
alert("FILE SIZE " + blob.size);
}
img.src = imgSrc;
}
function canvasToFile(dataUrl) {
var encData = dataUrl.split(',')[1],
binString = atob(encData),
binData = new Uint8Array(binString.length),
i, blob;
for (i = 0; i < binString.length; i++) {
binData[i] = binString.charCodeAt(i);
}
blob = new Blob([binData], {
type: 'image/jpeg'
});
return blob;
}
<p>Try uploading different image file and see the difference in size for same output resolution:</p>
<input type="file" id="f">
What you are experiencing is that the default type argument for canvas.toDataURL(type, encoderOptions) is image/png, and also that it's actually a base64 encode of the image data.
For the former, most browsers do support image/jpeg as image type. This may reduce the data size, thanks to jpg compression, but this will above all enable the encoderOptions parameter of the method, which could be translated to quality parameter and requires a 0 to 1 float.
Note that you can't be sure that the data will be lighter if converted into jpg though : if the image is mainly composed of transparent pixels, then png will be lighter. Also, remember that jpeg compression will reduce the quality of your image, see the last snippet to see what 0 results in :)
For the later, ( you can find an explanation of the why here ), the solution is to transform back the dataURL to a blob.
Here is a snippet to demonstrate it :
var input = document.querySelector('input');
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
function draw(){
var img = new Image();
img.src = URL.createObjectURL(this.files[0]);
img.onload = function(){
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0,0);
var noData = canvas.toDataURL();
png_data.innerHTML = 'dataURL length: '+noData.length;
var noBlob = dataURItoBlob(noData);
png_blob.innerHTML = 'blob size: '+ noBlob.size;
var jpgData10 = canvas.toDataURL('image/jpeg', 1),
jpgData5 = canvas.toDataURL('image/jpeg', 0.5),
jpgData0 = canvas.toDataURL('image/jpeg', 0);
jpg_data.innerHTML = 'quality = 1 : '+ jpgData10.length+'<br>';
jpg_data.innerHTML += 'quality = 0.5 : '+ jpgData5.length+'<br>';
jpg_data.innerHTML += 'quality = 0 :'+ jpgData0.length+'<br>';
var jpgBlob10 = dataURItoBlob(jpgData10);
jpg_blob.innerHTML = 'blob quality = 1 : '+jpgBlob10.size+'<br>';
var jpgBlob5 = dataURItoBlob(jpgData5);
jpg_blob.innerHTML += 'blob quality = .5 : '+jpgBlob5.size+'<br>';
var jpgBlob0 = dataURItoBlob(jpgData0);
jpg_blob.innerHTML += 'blob quality = 0 : '+jpgBlob0.size;
}
this.previousElementSibling.innerHTML = 'orginal size : '+this.files[0].size;
}
input.onchange = draw;
// Taken from https://stackoverflow.com/a/5100158/3702797
function dataURItoBlob(dataURI) {
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
<div></div>
<input type="file"/>
<br>PNG :
<div id="png_data"></div>
<div id="png_blob"></div>
<br>Jpeg :
<div id="jpg_data"></div>
<div id="jpg_blob"></div>
canvas.toDataURL('image/jpeg', 0) demo ?
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
document.querySelector('input').onchange = function(){
var img = new Image();
img.src = URL.createObjectURL(this.files[0]);
img.onload = function(){
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0,0);
document.images[0].src = canvas.toDataURL('image/jpeg', 0);
}
}
<input type="file"/>
<img/>
Also, if you need to make your file lighter than a specific size, I wrote something on another question, which limited the data size to 3Mb (just change maxSize to your needs and remove the localStorage part).