Download generated canvas with blobs - image

I am working on a project which generates an image on the HTML Canvas, and then offers to download the image as a PNG.
The program has to be clientside (javascript).
I can convert the canvas to image by using
var canvas=document.getElementById('canvas');
var img = canvas.toDataURL("image/png;base64");
And the code that is supposed to download the picture is:
var container = document.querySelector('#container2');
//container2 is a div in HTML
var output = container.querySelector('output');
//output is inside container2
window.URL = window.webkitURL || window.URL;
var prevLink = output.querySelector('a');
if (prevLink) {
window.URL.revokeObjectURL(prevLink.href);
output.innerHTML = '';}
//removes the download link if already there
var bb = new Blob([img], {data: "image/png;base64"});
//creates new blob from the img variable
var a = document.createElement('a');
a.download = 'test' + '.png';
//file name
a.href = window.URL.createObjectURL(bb);
//create URL from blob
a.textContent = 'Click here for download';
a.dataset.downloadurl = ["image/png;base64", a.download, a.href].join(':');
output.appendChild(a);
This works perfectly if the blobvariable is a string of text instead of the "img" variable. Instead of an image, I get af corrupted .png file which, opened in notepad gives data:image/png;base64,iVBORw0KGgoAAAANSUhEU...(long string of base64 letters), which is the correct string, but apparantly not good for PNG images. But if I write
document.write('<img src="'+img+'"/>');
The image is opened correctly in a new tab.
How can i make the downloaded image uncorrupted?
(it seems impossible to download the data generated by Canvas2image )

looks like you need to convert the base64 string back to a blob. here's how:
Base64 encoding and decoding in client-side Javascript
The document.write might work on some browsers, if they are able to handle base64 natively.
The other problem is that JavaScript usually works with string, but to download the file you need something like a ByteArray. Here's an implementation, I've found: https://github.com/danguer/blog-examples/blob/master/js/base64-binary.js
That's how I got it working then:
var ab = Base64Binary.decodeArrayBuffer(img.substring(22));
var bb = new Blob([ab]);
var a = document.createElement('a');
a.download = 'test' + '.png';
a.href = window.URL.createObjectURL(bb);
a.textContent = 'Click here for download';
output.appendChild(a);

Related

How to download navigator.getMediaStream audio blob on stop recording in .wav format in Firefox

I want to record an audio using navigator.getMediaStream and download it in .wav format but currently it gets downloaded in the '.ogx' format in Firefox browser.
I have tried by using audio/wav type in blob but still it's downloading in .ogx format instead of .wav format.
const blobDataInWavFormat: Blob = new Blob([blobDataInWebaFormat], { type : 'audio/wav; codecs=0' });
const anchor = document.createElement('a');
document.body.appendChild(anchor);
anchor.style = 'display: none';
const url = window.URL.createObjectURL(blob);
anchor.href = url;
anchor.download = 'audio.wav';
anchor.click();
window.URL.revokeObjectURL(url);

Xamarin Forms Convert from Image to Base64 from Image Control not from file

I am loading an image from the camera into an Image control. That works beautifully as shown below.
var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
if (photo != null)
PhotoImageRear.Source = ImageSource.FromStream(() => { return photo.GetStream(); });
I sometime later need to take the images loaded into that PhotoImageRear control and convert it to a base64 string in order to post it to an API.
What would be the most efficient way of achieving that.
Thanks in advance for your help
From shared code ,once you get the photo, you can use the following code to convert to Base64 .
var stream = photo.GetStream();
var bytes = new byte [stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
string base64 = System.Convert.ToBase64String(bytes);

Google Apps Script - Convert base 64 Image source to an image file

Here is an example of an image tag with the image source as base 64 data. The base 64 data is a smiley face.
<img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
I want to use base64 data to create an image file in Google Drive.
I've tried the following code, which runs, and creates a file with no errors, but it won't open as an image file.
function createImageFileFromBase64() {
var data = 'R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7';
var imageBlob = Utilities.newBlob(data, 'image/png');
var resource = {
title: 'AAA Test_Image',
mimeType: 'image/png'
}
var theReturn = Drive.Files.insert(resource,imageBlob );
Logger.log('file ID: ' + theReturn.id);
}
My goal is to make an image file without making an external request to an image file. I want the image data to be "hard coded" into the script.
Create the blob using byte array created by decoding the base64 string:
var imageBlob = Utilities.newBlob(Utilities.base64Decode(data), 'image/png');

Jscript image tag creation gives an error

function pushImage () {
var img = new Image();
img.src = '/waroot/chart/chart.png';
document.getElementById("test1").innerHTML = "<img src='/waroot/chart/chart.png'>";
document.getElementById("test2").innerHTML = img;
}
Test 1 works and shows the image, but test 2 doesn't. I am not sure how to solve it but i will need the way test 2 works further along my project since i'm going to have to circle through a large amount of images.
The images are created by JFreeCharts, saved to png and then have to be posted to a site. As a side question: is it possible to push the freecharts objects straight to the jscript instead of having to save them prior (i could throw them into the dictionary and then look them up later but i'm not sure if this works)
Use .appendChild(img) instead of .innerHTML:
function pushImage () {
var img = new Image();
img.src = '/waroot/chart/chart.png';
document.getElementById("test1").innerHTML = "<img src='/waroot/chart/chart.png'>";
document.getElementById("test2").appendChild(img);
}
Demo
This is because img is an image object, not an html string, so you have to append it to the DOM.
P.S., don't forget that the alt attribute is required in the img tag!

importing image on canvas html5

var img = new Image();
img.src = '/images/backdrop.jpg';
ctx.drawImage(img,0,0);
I wanted to load an image from local disk on to canvas using dialog box mechanism rather than the path directly specified as in above example. I tried different sorts using JavaScript but in vain, even tried using the input type as file. What else can I try?
Take a look here:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images
It's important to have drawImage call after the image has loaded:
var img = new Image();
img.onload = function() {
var ctx = document.getElementById('ctx').getContext('2d');
ctx.drawImage(img, 0, 0);
}
img.src = 'images/backdrop.jpg';
Also, note that you probably want to use images/backdrop.jpg instead of /images/backdrop.jpg (note there's no slash in front), as using the latter would get the image from root directory, I would assume that's probably not where your images are.
As far as loading from a dialog box, you can replace the last line from the above with something like this:
var name = prompt("Enter the name of the file", "backdrop.jpg");
img.src = 'images/' + name;
This way, the user would be able to enter the name of the image file to load it. Of course, you need to have that file in your images folder.
Hope this helps.

Resources