Reputation: 770
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?
Upvotes: 3
Views: 39764
Reputation: 21
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();
}
}
Upvotes: 0
Reputation: 692
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
Upvotes: 1
Reputation: 1789
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));
Upvotes: 3
Reputation: 24342
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.
Upvotes: 1