Convert image into base64string in JQuery - javascript

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.
});
}

Related

Cannot read property 'width' of undefined whille converting image into base64?

I want to convert my image into base64 format and send to server .I tried to convert my image base64 but getting error this
Cannot read property 'width' of undefined function
getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
$(function(){
// alert()
$('#fileId').on('change', function (e) {
console.log('ddd');
var file = e.target.files[0];
console.log(getBase64Image(handleImage(e)))
})
})
here is my code
https://jsbin.com/zagagivuje/edit?html,js,console,output
I attached one image and try to get base64 string then I am getting this error
Checkout this link
What I'm doing here is basically create an image from file url and draw that image on canvas and rest is your code.
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, img.width, img.height);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
function handleImage(e, callback) {
var img = new Image();
img.onload = function(event) {
let r = getBase64Image(img);
callback(r);
};
img.src = URL.createObjectURL(e.target.files[0]);
}
$(function() {
// alert()
$('#fileId').on('change', function(e) {
var file = e.target.files[0];
handleImage(e, function(r) {
console.log(r);
});
})
})
Return some value from your handleImage() function.
Your function handleImage() does not return any value. So, when you are doing console.log(getBase64Image(handleImage(e))) in the last lines of your code, nothing would get passed in as a parameter for the function getBase64Image(). Thus, the value of img in the function getBase64Image() is undefined and so you get the error Cannot read property 'width' of undefined when you try to read img.width on the third line of your code where img is undefined.

When I try to upload an image as canvas through FileReader, I need to upload twice, else it is a blank image that gets posted

I'm trying to upload an image with FileReader() and convert it to base64. This only works when after I upload the image twice, otherwise, a blank canvas/image gets posted instead.
This is my input:
<input type="file" id="file" class="file"/><canvas id="canvas"></canvas>
This is the FileReader():
var file = document.querySelector('input[type=file]').files[0];
var fr = new FileReader();
fr.onload = createImage; // onload fires after reading is complete
fr.readAsDataURL(file); // begin reading
function createImage() {
img = new Image();
img.onload = imageLoaded;
img.src = fr.result;
}
function imageLoaded() {
var canvas = document.getElementById("canvas")
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
}
var img64 = canvas.toDataURL().split(",")[1];
var params = {
"media_data": img64
};

Base64 encoding an image alerts correct, response is nil

I'm trying to encode an image in Base64 from a URL.
function getBase64Image(url) {
var img = new Image(),
response = '';
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL('image/png');
response = dataURL;
alert(response);
};
img.src = url;
return response;
}
The alert() works fine but the response is nil:
You can see in the console in the screenshot if I log the response like so (it's done twice in the screenshot) it returns nothing:
console.log(getBase64Image('<%= asset_path "test.jpg" %>'));
Obviously we can read the image because the alert has the encoding. What am I missing?
Update
Relevant JSFiddle: https://jsfiddle.net/guxzxq20/3/
Approach: Canvas
Load the image into an Image-Object, paint it to a non-tainted canvas and convert the canvas back to a dataURL.
function convertImgToDataURLviaCanvas(url, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
call method
convertImgToDataURLviaCanvas('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png',function(response){
alert(response)
});
I believe you are returning the empty response object that you have created, because the response object inside the onLoad() function is not accessing the outside response.
Try changing your code to calling a callback once the onload() function reaches its end, and using that callback to alert.
Something like:
function getBase(url, callback) {
// ... code
img.onload = function () {
// ... code
callback(response);
}
}
This was a very raw example.

Base64 convert from image not getting base64 string

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!!

Unable to load an Image into Canvas and get base64 encoding for that image

I am trying to generate a PDF from HTML using jspdf plugin. I am stuck with loading Images into PDF. There is a function addImage() in plugin which takes base64 encoding of an image, but converting an image to base64 is not working.
I have used below two ways
//Create canvas, draw image in context and get the data url
imgToDataURL = function (img, outputFormat){
var canvas = document.createElement('canvas');
canvas.width = 20;
canvas.height = 20;
var c = canvas.getContext('2d');
c.height = img.height;
c.width=img.width;
c.drawImage(img, 0, 0);
c.save();
var dataurl = canvas.toDataURL(outputFormat);
return dataurl;
}
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = "image path"
img.height= 60;
img.width=60;
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
This is printing wrong dataURL I am getting a white image. If I hard code the base64 code i.e return a hardcoded dataURL then addImage works fine. So the issue is with canvas.toDataURL which is giving me wrong output
this is the 2nd way
convertImgToBase64URL = function (url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
this.convertImgToBase64URL("Image Path",function(base64){
renderer.pdf.addImage(base64, 'PNG', 20, 20,48,48);
})
I have run this inside a javascript and the onload function is not even running I am not sure what is my mistake is.
Please suggest me what mistake I am doing in either way
In the first you missed assigning an onload function to your image. For that reason, the moment you try to create the dataURL, the image might not be loaded yet, ergo, the blank image. You could try changing the last few lines to this:
...
img.width=60;
img.onload = function () {
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
}
img.src = "image path";
As for the second one, there seems to be a problem with the convertImgToBase64URL() which accepts 3 parameters, but you are passing 2. In you example, outputFormat parameter is undefined.

Categories

Resources