Convert png blob to jpg blob in javascript - html5-canvas

i have below png blob which i want to convert to jpg blob. How can i achieve that?
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgQAAAK2CAYAAAAxAIToAAAAAXNSR0IArs4c6QAAIABJREFUeF7s......

You will have to redraw your blob using html canvas then convert it back to jpg blob, as follows:
var img = await document.createElement("img");
img.src = 'your_base_64_blob_string_here'
img.onload = function (event) {
// This line is dynamically creating a canvas element
var canvas = document.createElement("canvas")
var ctx = canvas.getContext("2d");
//Resize your image here
ctx.drawImage(img, 0, 0, 400, 350);
// To blob
var jpgBlob = await new Promise(resolve => canvas.toBlob(resolve,'image/jpg', 1)); // refer to canvas.toblob API
// To file
var jpgFile = await new File([jpgblob], imagefilename.jpg, {type:'image/jpg'}); // refer to File API
}
I have not tested the code, please inform if it works. Be aware of browser compatibility.
Your can also get more information on this these similar posts (Don't worry about the title follow the answers):
How to convert Blob to File in JavaScript
Convert blob to image file

Related

How to convert render from three.js to .png file?

How would I convert a render to a .png image?
I've been looking around for awhile but nothing has worked.
Here is a function I use and a fiddle that shows it working.
function takeScreenshot() {
// For screenshots to work with WebGL renderer, preserveDrawingBuffer should be set to true.
// open in new window like this
var w = window.open('', '');
w.document.title = "Screenshot";
//w.document.body.style.backgroundColor = "red";
var img = new Image();
img.src = renderer.domElement.toDataURL();
w.document.body.appendChild(img);
// download file like this.
//var a = document.createElement('a');
//a.href = renderer.domElement.toDataURL().replace("image/png", "image/octet-stream");
//a.download = 'canvas.png'
//a.click();
}

How to display an image offline using Famo.us

How can you display an image that can be used offline using Famo.us?
A Famo.us Image surface sets it's content based on an image URL. However, when offline, this URL will not work. I have tried using an HTTP request and converting the buffer to a Blob and then creating a URI for the Blob:
// bytes = request.buffer of HTTP request
// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/jpg'});
// Use createObjectURL to make a URL for the blob
imageURL = URL.createObjectURL(blob);
//Use Famo.us image surface API to display the image (http://famo.us/docs/api/latest/surfaces/ImageSurface)
imageSurface.setContent(imageURL);
This does not throw any warning or errors but displays a broken image. Any suggestions? I want to display an image even when I am offline, but when I reconnect I will request for the newest image uploaded.
ImageSurface in Famo.us can take a url to the image or the base-64 encoded data.
Using Blob:
Use the file reader to readAsDataURL
var reader = new FileReader();
reader.onloadend = function () {
imageURL = reader.result;
}
reader.readAsDataURL(blob);
Using Canvas:
There are plenty of ways to get the encoded base-64 data. Canvas has another way to get this string for you.
Example jsBin Here
Using the example snippet below, you can see how you can use Canvas.toDataURL.
var image = new Image();
image.crossOrigin = 'anonymous'; // only needed for CORS, not needed for same domain.
// create an empty canvas element
var canvas = document.createElement("canvas");
var canvasContext = canvas.getContext("2d");
image.onload = function () {
//Set canvas size is same as the picture
canvas.width = image.width;
canvas.height = image.height;
// draw image into canvas element
canvasContext.drawImage(image, 0, 0, image.width, image.height);
// get canvas contents as a data URL (returns png format by default)
imageURL = canvas.toDataURL();
};
image.src = 'http://code.famo.us/assets/famous_logo.png';

How to get base64 image data without call canvas toDataURL?

I'm on a project which requires to support ie9 or ie10.
I'm using d3.js for data visualization.
Now I need to provide a function to export the chart as pdf.
I have been investigate into possible solutions. It seems that canvas + jsPdf is the way to go, below is some code I write.
But the problem is that when toDataURL gets called, it will cause security errors on IE9 and IE10. So I'm wondering if there's some work around to get base64 image data without using canvas since jsPdf only needs base64 image data???
createObjectURL to the root svg element
svgElement = $('svg').get(0);
serializer = new XMLSerializer();
str = serializer.serializeToString(svgElement);
DOMURL = window.URL || window.webkitURL || window;
url = DOMURL.createObjectURL(new Blob([str], {type: 'image/svg+xml;charset=utf-8'}));
draw an image using canvas
img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0);
imgData = $canvas.get(0).toDataURL("image/jpeg");
DOMURL.revokeObjectURL(url);
pdf = new jsPDF('landscape', 'pt', 1000, 800);
pdf.addImage(imgData, 'JPEG', 0, 0);
pdf.save('download.pdf');
};
img.src = url;
I finally find the solution which is to use an open source project: canvg

how to merge two images in windows phone and save it to isolated storage

I want to merge two images,one image is of 300x300 and other is 100x100, First i have created a canvas and then i created two images which i have added to the both the images to canvas and the canvas is added to the content panel, then i created a writeablebitmap and render the canvas and created a method savejpeg which saves the image to isolated stoarage,but isolated storage is not showing the whole image it save a black screen.
First i created a canvas through code set its height width and background color then i created two images programmatically which i have added to the canvas and then canvas is added to the contentpanel
my code is:
public void CreateImage()
{
Canvas canvas = new Canvas();
canvas.Height = 400;
canvas.Width = 400;
canvas.Background = new SolidColorBrush(Colors.Red);
Image img1 = new Image();
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("Image/Desert.jpg");
img1.Height = 300;
img1.Width = 300;
img1.Margin = new Thickness(0, 10, 0, 0);
Image img2 = new Image();
img2.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("Image/Jellyfish.jpg");
img2.Height = 50;
img2.Width = 50;
img2.Margin=new Thickness(0,10,300,0);
canvas.Children.Add(img1);
canvas.Children.Add(img2);
ContentPanel.Children.Add(canvas);
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(canvas, new MatrixTransform());
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms,400,400,0,100);
using (var isoFileStream = new IsolatedStorageFileStream("myPicture.jpg", FileMode.OpenOrCreate, IsolatedStorageFile.GetUserStoreForApplication()))
{
wb.SaveJpeg(isoFileStream, 400, 400, 0, 100);
}
}
When i save the image then i am getting a black screen in isolated storage.
How to save both images on canvas?
Like Stephan said, I think you are not getting the image to your source. Any way I created a sample application for you. In that you can find two partitions, you can add image to that by double tapping on the container. After that try save and check your saved image. I tested the app and every thing is working for me. Still you face any kind of issues please leave a comment.
https://www.dropbox.com/s/1vjbbou96w0r15r/SaveImageApp.zip
Please check weather you are getting image or not to image source. If you are getting the image; try this method to take snapshot from control and save that to Iso store.
http://stackoverflow.com/questions/13837148/how-can-i-take-a-screenshot-full/13990649#13990649

html5: copy a canvas to image and back

I implemented a zoom in and out function on a canvas element.
it works by scaling the canvas, translating it, and then redraw the whole scene again.
the problem is that it takes a lot of time to redraw everything because i got a lot of things on my canvas.
I need a way to copy the canvas to an image object and than copy the image back to the canvas without loosing quality. what are the specific methods to copy canvas to a javascript variable, and to to copy this variable back to the canvas later?
I'll be glad if you write down the code because I couldn't find any good explanation over the internet.
thanks,
The drawImage() method can draw to a canvas using another canvas instead of an image.
You could create a 'backup' canvas, of the same size as your original, draw the first one to there and then draw that one back to the original when you need it.
e.g.
// Assume we have a main canvas
// canvas = <main canvas>
ctx = canvas.getContext('2d');
..
// create backing canvas
var backCanvas = document.createElement('canvas');
backCanvas.width = canvas.width;
backCanvas.height = canvas.height;
var backCtx = backCanvas.getContext('2d');
// save main canvas contents
backCtx.drawImage(canvas, 0,0);
..
// restore main canvas
ctx.drawImage(backCanvas, 0,0);
There are a few ways to do it theres the getImageData and putImageData methods Reference, However putImageData and getImageData are pretty slow. Another way is to save the data to an image in memory and recall it from that which is much faster, then the third way is the one above mentioned by andrewmu which involves copying to another canvas element. I have included examples for the first and second type.
Image in memory method
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
savedData = new Image();
function save(){
// get the data
savedData.src = canvas.toDataURL("image/png");
}
function restore(){
// restore the old canvas
ctx.drawImage(savedData,0,0)
}
getImageData putImageData method
// Setup our vars, make a new image to store the canvas data
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
canvasData = '';
function save(){
// get the data
canvasData = ctx.getImageData(0, 0, 100, 100);
}
function restore(){
// restore the old canvas
ctx.putImageData(canvasData, 0, 0);
}
added image into canvas
var image = new Image();
image.src = "1.jpg";
image.onload = function () {
context.drawImage(image, 0, 0);
};

Resources