The multipart upload example here mentions JPEG data . What exactly is it ? How do I fetch it out of an HTML IMG element ? I tried sending the dataUri ( after creating a canvas with drawImage() and extracting its dataUri ; it did not work .
this.sendToDrive = function () {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = document.createElement("img");
var that = this;
img.addEventListener("load", function () {
ctx.drawImage(img, 0, 0);
var dataUrl = canvas.toDataURL("image/jpeg", 1);
//window.open(dataUrl);
var binaryData = dataUrl.replace(/^data:image\/(png|jpeg);base64,/, "");
that.transmitFile(dataUrl, that.title(), token);
});
img.setAttribute("src", this.src);
canvas.width = img.width;
canvas.height = img.height;
}
I do get the complete image in a new tab (window.open() ), but if I transmit it using the 'transmitFile()' method - which simply sends a multipart post to google drive and leads to a 200 ,and download the file created in the drive, it does not work. I leads to errors like Error interpreting JPEG image file (Error interpreting JPEG image file (Not a JPEG file: starts with 0x2f 0x39)) . The data url is correct for sure, but is it what needs to be sent as the 'jpeg data' ? I get similar errors if I use window.btoa(dataUrl) or window.atob(dataUrl).
Related
I have in the client side a JS script which gets some Canvas, converts it to a DataURL, and send it through some FormData.
let image = canvas.toDataURL("image/png");
let formData = new FormData();
formData.append('Canvas_Image', image);
How can I save it in Deno (using Oak) as a file image?
The issue is now solved, so here are the results.
First, as the method toDataURL converted the canvas image into a Base64 string, I have used the standard library of Deno for the encoding/decoding methods:
import { decode as base64Decode, encode as base64Encode } from 'https://deno.land/std#0.82.0/encoding/base64.ts';
// Read the FormData in Oak server:
const body = await request.body({ type: 'form-data'});
const form = await body.value.read();
// Get the Image from the FormData (wich comes encoded in a base64 string)
let Image = form.fields.Canvas_Image;
// Replace characters so the decoding has no problems.
Image = Image.replace("data:image/png;base64,", "");
Image = Image.replace(" ", "+");
// Use this method from the std library to decode it:
let DecodedImage = base64Decode(Image);
// Save the decoded image using Deno.writeFile()
let URI_Image = "./path/to/save/your/image.png";
await Deno.writeFile(URI_Image, DecodedImage);
And that's all, it should save your image in the server correctly.
I have problems to drag an image from one iframe (1) out of a dynamic table to another iframe (2) within a droppable area. I think there is no permission issue, but a "type" issue. The drop area on iframe (2) is working with files from anywhere except form the iframe (1). The iframe (1) is hosted by localhost. The iframe (2) is hosted by a different domain.
Three different functions I found to convert data uri to file or blob were tested. The setData arguments also have been tested with all possibilities, no success by now.
Interestingly, having opened the site with the two iframes on Chrome and firefox, I am able to drag an drop from firefox to Chrome, but the image will be converted to bmp type and renamed! The other way around it is not working.
What are the right arguments for setData / get Data to drop an image
data uri on a drop area?
Do I have to convert data uri to a file
resp. blob object?
If so, again, what arguments will do the job?
Any help would be appreciated very much!
var dataUri;
var file;
function mouseDown(event){
toDataURL(event.target.src, function(dataUrl) {
console.log('RESULT:', dataUrl.replace('data:text/plain;base64,', ''));
dataUri = dataUrl.replace('data:text/plain;base64,', '');
file = urltoFile(dataUrl, 'hello.jpg','image/jpeg')
.then(function(file){ console.log(file);});
})
}
function drag(event) {
// event.stopPropagation();
console.log(file);
console.log(dataUri);
event.dataTransfer.setData("text/plain", file);
//event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
event.dataTransfer.effectAllowed = "move";
}
function drop(event) {
//event.preventDefault();
console.log(file);
console.log(dataUri);
var data = event.dataTransfer.getData("text/plain");
//var data = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0);
event.target.appendChild(document.getElementById(data));
document.getElementsById(data);
console.log(data);
}
function allowDrop(event) {
event.preventDefault();
}
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
function urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename,{type:mimeType});})
);
}
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var dw = new DataView(ab);
for(var i = 0; i < byteString.length; i++) {
dw.setUint8(i, byteString.charCodeAt(i));
}
// write the ArrayBuffer to a blob, and you're done
return new Blob([ab], {type: mimeString});
}
UPDATE
now its working, see the answer below (https://stackoverflow.com/a/43983621/2844901)
this is my getDrawing function, I need to save the signature from drawing to a file in file system, I've tried everything and I cant get the saveToFile demo in nativescript docs to get it work.
exports.getDrawing = function(args) {
var pad = frameModule.topmost().currentPage.getViewById("drawingPad");
// then access the 'drawing' property (Bitmap on Android) of the signaturepad
var img = frameModule.topmost().currentPage.getViewById("imagesignature");
pad.getDrawing().then(function(result){
img.src = result; // <-- this shows in an image label the drawing signature
########### this part should be save the file,but I don't get any error, and it doesn't save it to a file, when tried to dump "img" ############
var img2 = imageSource.fromAsset(result);
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = img2.saveToFile(path, "png");
});
}
the problem was, the getDrawing() does not return a promise it returns an image so the correct code should be a NativeSource.
pad.getDrawing().then(function(result){
img.src = result;
console.log("1");
var img2 = imageSource.fromNativeSource(result);
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = img2.saveToFile(path, "png");
console.log("saved: " + saved);
console.log("IMAGEN SRC.....");
});
I am fetching contacts from phone along with their images in phonegap.I have to save those images to my local database in Base64 or byte-array, So that later i can send those data to server also.
I am able to convert image into Base64 but this process is synchronous.
Let suppose i have 10 Contacts in my phone in which 5 contacts have image and rest has not.
so when i am applying loop for saving those images,so that time contacts who have images takes time to change images to Base64 mean while contacts who doesn't have images store in database because for these 5 contacts no need to change image to Base64.
So only 5 contacts get inserted in database and i get the Base64 of those 5 contacts after completing the loop.
I want that in loop untill i get the Base64 of any image, loop index should not increase by 1. As i get the Base64 of image after that i should move to next index.
This is the method which i am using for Converting any image to Base64.
function convertImgToBase64(url, callback, outputFormat){
alert(url);
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
//alert("URL "+url);
//alert("dataURL " + dataURL);
alert(dataURL);
callback.call(this, dataURL);
// Clean up
canvas = null;
};
img.src = url;
}
Can anyone please help me.
The following code is supposed to read an image file and then add the file data into a canvas with the help of the Canvas module.
When I run this code I receive the error message Image is not defined. Is the image object that I'm trying to initialise from a module that I simply import?
var http = require('http'), fs = require('fs'),
Canvas = require('canvas');
http.createServer(function (req, res) {
fs.readFile(__dirname + '/image.jpg', function(err, data) {
if (err) throw err;
img = new Image();
img.src = data;
ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);
res.write('<html><body>');
res.write('<img src="' + canvas.toDataURL() + '" />');
res.write('</body></html>');
res.end();
});
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
I apologize if I'm wrong here, but it looks like you've found this code somewhere and tried to use it without actually understanding what's happening under the covers. Even if you were to fix the Image is not defined error, there are many others.
I have the fixed code at the end of this post, but I'd recommend thinking more deeply about these issues in the code from your question:
What is Image? Where does it come from? You've imported http, fs, and Canvas, so those things are obviously defined. However, Image hase not been defined anywhere and it is not a built-in.
As it turns out, Image is from the node-canvas module, which you've imported with Canvas = require('canvas'). This means that Image is available as Canvas.Image.
It's important to understand that this is because of the imports you've setup. You could just have easily have done abc = require('canvas'), and then Image would be available as abc.Image.
What is ctx? Where is that coming from?
Again, this is another variable that just hasn't been defined anywhere. Unlike Image, it isn't available as Canvas.ctx. It's just a random variable name that doesn't correspond to anything at this point, so trying to call drawImage on it is going to throw an exception.
What about canvas (lowercase)? What is that?
You are using canvas.toDataURL, but there is no variable called canvas anywhere. What are you expecting this piece of code to do? Right now it's just going to throw an exception saying that canvas is undefined.
I'd recommend reading documentation more closely and looking more closely at any example code you copy into your own applications in the future.
Here is the fixed code, with some comments to explain my changes. I figured this out by taking a quick look at the documentation at https://github.com/learnboost/node-canvas.
var http = require('http'), fs = require('fs'),
Canvas = require('canvas');
http.createServer(function (req, res) {
fs.readFile(__dirname + '/image.jpg', function(err, data) {
if (err) throw err;
var img = new Canvas.Image; // Create a new Image
img.src = data;
// Initialiaze a new Canvas with the same dimensions
// as the image, and get a 2D drawing context for it.
var canvas = new Canvas(img.width, img.height);
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);
res.write('<html><body>');
res.write('<img src="' + canvas.toDataURL() + '" />');
res.write('</body></html>');
res.end();
});
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
node-canvas now has a helper function, loadImage, that returns a Promise resolving to a loaded Image object. This prevents having to mess around with onload handlers like in the accepted answer.
const http = require('http');
const fs = require('fs');
const Canvas = require('canvas');
http.createServer(function (req, res) {
fs.readFile(__dirname + '/image.jpg', async function(err, data) {
if (err) throw err;
const img = await Canvas.loadImage(data);
const canvas = new Canvas(img.width, img.height);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);
res.write('<html><body>');
res.write('<img src="' + canvas.toDataURL() + '" />');
res.write('</body></html>');
res.end();
});
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');