how to create an image file on server from dataurl - javascript

I have an image in a dataurl format, like:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwME…iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/2Q==
I need to convert this string in JavaScript to another string which can be directly copied to a blank jpg file so that it can be viewed by the user.
Any idea how to achieve this?

You just need to remove "data:image/jpeg;base64," from DataURI.
$dataUri = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgM...";
// remove "data:image/jpeg;base64," from image Data URI.
$data = str_replace("data:image/jpeg;base64,", "", $dataUri);
// save to file
file_put_contents("/tmp/image.jpeg", base64_decode($data));

If you want the user to be be able to download the file and save it somewhere on their computer, try this:
document.location.href = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB…";
See Download data url file if this is what you're trying to do.

To display it you can use the src attribute:
<img src="data:image/png;base64,R0lGODlhUAAPAKIAAA+g4JADs=" width="80" height="80" />
To generate a file you need use canvas element:
Example:
<html>
<head></head>
<body>
<canvas id="c"></canvas>
<script type="text/javascript" src="canvas2image.js"></script>
<script type="text/javascript" src="baseg4.js"></script>
<script type="text/javascript">
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = "data:image/png;base64,iVBORw0KG............5CYII%3D";
image.onload = function()
{
ctx.drawImage(image, 0, 0);
var foo = Canvas2Image.saveAsPNG(canvas);
};
var img = canvas.toDataURL("image/png");
</script>
</body>
</html>
And save the image and stuff... you can find a way to convert the canvas to a file in this link:
// http://www.nihilogic.dk/labs/canvas2image/
EDIT: New link, I guess...
https://github.com/hongru/canvas2image

You have to remove data:image/jpeg;base64, from the dataURI and decode the dataURI:
public void saveImage(String imageURI) {
BufferedImage image = null;
String blobString=imageString.replace("data:image/jpeg;base64,", "");
byte[] byteArray = Base64.getDecoder().decode(blobString);
ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
try {
image = ImageIO.read(bis);
File file = new File("/home/rakesh/Vinay/a.jpeg");
ImageIO.write(image, "jpeg", file);
} catch (IOException e) {
e.printStackTrace();
}
}

Related

how to pass Image data uri from javascript to php

I have a webpage which displays a chart. I had to generate a pdf of this chart. So I wrote this code to capture the chart as an image and put inside the pdf. I used html2canvas for this which generated a data uri for the image. Now I am stuck with this uri in javascript. The pdf code is a php script which needs this uri. How do I do this ?
The chart.php generates the chart and using html2canvas stores the image datatauri into localstorage.
CHART.PHP
<script>
//<![CDATA[
(function() {
window.onload = function(){
html2canvas(document.getElementById('chart'), {
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
console.log(canvas.toDataURL("image/png"));
window.localStorage.setItem("imgURL", canvas.toDataURL("image/png"));
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
//alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>
<body>
<a href="pdfGen.php" id="download" >Report</a>
</body>
This is the php script which generates the pdf using fpdf library
pdfGen.php
<?php
/*$pdf = new FPDF();
$pdf->AddPage();
//over here I want to add the image from the chart.php page whose data url is now in the localstorage.
..more code to generate report
$pdf->output();*/
?>
How do i send the such a big uri to this php script ? Trying an ajax wont work as I need to redirect to this php page. Also sending the uri along in the url wont work either as the url becomes too large and goes beyond its capacity.
In your script :
<script>
document.getElementById('imageURL').value=canvas.toDataURL("image/png");
</script>
create a form in ur body with a report button and an hidden field for URL :
<body>
<form action="pdfGen.php" id="download" method="post">
<iput type="hidden" id="imageURL" name="imageURL"/>
<input type="submit" value="Report" name="submit"/>
</form>
</body>
In your php page - pdfGen.php
<?php
$imageURL = $_REQUEST['imageURL'];
?>
Hope it helps.
EDIT
<script>
//<![CDATA[
(function() {
window.onload = function(){
html2canvas(document.getElementById('chart'), {
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
console.log(canvas.toDataURL("image/png"));
document.getElementById('imageURL').value=this.src;
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
//alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>
You can also creaate file from base64 and send it to server, like in this post (works from ie10 and all modern browsers)

Display a generated gif;base64 image using C# code behind in img using JavaScript

i have the following C# code behind (it is a code that generate dynamically an Bmp image and than convert it to gif and returns it to be displayed):
[WebMethod]
public static HtmlImage ProcessIT()
{
var bitmap = DrawingMethod(); //Method that draws dynamically Bmp Image
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
var base64Data = Convert.ToBase64String(ms.ToArray());
HtmlImage img = new HtmlImage
{Src = "data:image/gif;base64," + base64Data, Width = 940};
return img; //The Gif image i want to display on the page
}
Than, I'm calling this C# behind code Method from : Generate_onclick() which is a JavaScript
function Generate_onclick()
{
PageMethods.ProcessIT(onSucess, onError);
function onSucess(result)
{
//Here is where i am not sure how it's done !!!!!!
document.getElementById("imgCtrl").src = result;
}
function onError(result)
{
alert('Something wrong.');
}
}
in here is the HTML Code :
<img src="" alt="" style="width: 100%;" runat="server" id="imgCtrl" />
is this the right way to display my image in the page ? if not than how ?
This is untested but I believe it should work. The point here is that if you want to continue with what you have you will want to return the base64 string and set the source of the html element to that string not to an html image object.
[WebMethod]
public static string ProcessIT()
{
var bitmap = DrawingMethod(); //Method that draws dynamically Bmp Image
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
var base64Data = Convert.ToBase64String(ms.ToArray());
string img = "data:image/gif;base64," + base64Data;
return img; //The Gif image i want to display on the page
}

FileReader readAsBinaryString() to Image DOM Element

If have an input type file
<input id="file" type="file" name="file" />
and an Image
<img id="img">
If a file is selected I want to read Exif data from the image an load it into the img tag.
var $inputFile = $("#file");
$inputFile.on("change", function() {
var img = document.getElementById("img");
var files = $inputFile[0].files;
var reader = new FileReader()
reader.onload = function(event) {
var file = reader.result;
// this is not working
img.src = file;
var binaryString = reader.result;
var oFile = new BinaryFile(binaryString, 0, file.size);
var exif = EXIF.readFromBinaryFile(oFile);
// read exif data
}
reader.readAsBinaryString(files[0]);
});
The problem is that I did not get any image on the screen. It only shows up if I use reader.readAsDataURL(files[0]); but this I cannot use because I need the binaryString for the Exif data.
How do I get the image tag to show the selected file which is a binary string?
to show an image in "binary" form, you need to have it as a base62 encoded string, aka "dataURL".
To use it binary and put it as the src you can make a ObjectURL.
var objectURL = URL.createObjectURL(blob);
image.src=objectURL;
You don't need a fileReader for this, but you will need fileReader for your exif analysis

read in a file from url or filesystem to variable in javascript

I am trying to read in a file from a file on my computer and store in in a variable.
I am currently trying:
var fr = new FileReader;
fr.onload = function() {
//variable to hold file
var data = fr.result;
var c=document.getElementById("cvs");
var ctx=c.getContext("2d");
ctx.drawImage(img,0,0,200,180);
};
fr.readAsDataURL("encryptedImage");
this does not work. I need to do this do i can decrypt an encrypted image on my file system. I have already turned of the security so my file system can be read from a browser.
any ideas?
From here it looks like you want to load the local file by passing a String to readAsArrayBuffer(), but it exspects a blob or file object. The file can be loaded via the browsers file dialog.
Steps are : Select the file, load the file via fileReader asArrayBuffer or asDataURL or asBinaryString ... and manipulate or use the data in your code.
For this example it creates an Image from the local file and draws it onto the canvas (if it's of correct mime type "image.*" however).
I'm not sure what kind of encoding/decoding you want to apply. But for custom manipulation of data I would recommend using ArrayBuffers and TypeArrays.
The example with FileReader.readAsDataURL(): http://jsfiddle.net/uvmD7/
<body>
<canvas id="cvs" width="200" height="200"></canvas>
<input type="file" id="files" name="files[]" multiple />
</body>
And the script:
document.getElementById('files').addEventListener('change', handleFileSelect, false);
var fr = new FileReader();
function handleFileSelect(evt) {
var files = evt.target.files;
fr.readAsDataURL(files[0]);
};
fr.onload = function(evt) {
// do sth with it
var data = evt.target.result; //fr.result
img = new Image();
img.src = data;
// draw after load
img.onload = function() {
var c=document.getElementById("cvs");
var ctx=c.getContext("2d");
ctx.drawImage(img,0,0,200,180);
};
};

downloading a javascript blob variable as mhtml

I'm writing a google chrome extension that uses
chrome.pageCapture.saveAsMHTML(object details, function callback)
function callback (blob mhtmlData) {...};
http://code.google.com/chrome/extensions/dev/pageCapture.html
which basically stores a blob representation of an mhtml page into a variable.
Now I want to let the user download this blob variable as an mhtml file..
I tried this but is gives me a 200kb file filled with random characters.
chrome.pageCapture.saveAsMHTML({tabId: sender.tab.id}, function callback(mhtml){
var reader = new FileReader();
reader.readAsDataURL(mhtml);
reader.onload = function(e) {
window.open(e.target.result);
}
});
Following is some code that I put in a page actions popup. I left the stuff that I didnt use but commented it out for reference.
EDIT:
Using the library from https://github.com/eligrey/FileSaver.js it was easy, maybe you could look at that to see what their doing.
popup.html
<html>
<head>
<script xmlns="http://www.w3.org/1999/xhtml" type="application/ecmascript" async="" src="https://raw.github.com/eligrey/FileSaver.js/master/FileSaver.min.js"></script>
<script>
function onLoad(){
var downloadLink = document.querySelector("#MHTML");
var oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
// None of the following worked
//window.open('data:application/octet-stream;'+oFREvent.target.result.slice(5));
//window.open('data:application/message/rfc822;'+oFREvent.target.result.slice(5));
//window.open(oFREvent.target.result);
};
chrome.tabs.getSelected(null, function(tab) {
chrome.pageCapture.saveAsMHTML({tabId: tab.id}, function (mhtml){
/// Works but requires user input
//downloadLink.setAttribute('download',tab.title+'.mhtml');
//downloadLink.setAttribute('href',window.webkitURL.createObjectURL(mhtml));
///Works but awful filename without extension
//window.open(window.webkitURL.createObjectURL(mhtml));
///Doesnt work
//oFReader.readAsDataURL(mhtml);
///Using https://github.com/eligrey/FileSaver.js , works great
saveAs(mhtml, tab.title+'.mhtml');
})
});
}
</script>
</head>
<body onload="onLoad();" style="width: 400px">
<a id="MHTML" href="#">Download Page As MHTML</a>
</body>
</html>
In case you want to give the file a name you could use an anchor element and set the name of the download attribute programmatically:
var reader = new FileReader();
reader.readAsDataURL(mhtml);
reader.onloadend = function(e) {
const dataUrl = e.target.result;
const a = document.createElement('a');
a.href = dataUrl;
a.download = fileName;
a.click();
}

Categories

Resources