Dyskusje » Tworzenie skryptów

Converting image format(png to jpeg/base64 png to base64 jpeg) for use in JSZIP.

§
Napisano: 04-11-2015

Converting image format(png to jpeg/base64 png to base64 jpeg) for use in JSZIP.

I was trying to convert image formats using the canvas method for use in JSZip but then I realised that I can't CORS enable it.
Currently using this method from SO to get image data which works if you want to directly put the image in the zip, but I need to also be able to convert image format.

Does anyone know any alternatives to canvas method? Preferably JQuery/JS based.

woxxomMod
§
Napisano: 04-11-2015

The canvas is tainted when real DOM images are used to paint it, but what about creating a base64-URL image out of GM_xmlHttpRequest's response?

var img = new Image();
img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH............'; 

canvas.drawImage(img);
var png = canvas.toDataURL("image/png");

Untested.

§
Napisano: 05-11-2015
Edytowano: 05-11-2015

I finally figured it out. Aside from doing as suggested, I also needed to execute toDataURL with an event listener(so that browser thinks this part is same origin).

For anyone who stumbles on this with the same problem here are the steps:

1. As suggested, create a new image with base64 version of desired image.
2. append new image to DOM
3. add event listener (in this case "load" because drawImage() requires source img to be loaded first)
4. With this listener, create new canvas, draw base64 image to canvas, use toDataURL("image/"+desiredformat) to convert.
5. profit

Ty wOxxOm.

§
Napisano: 14-11-2015
Edytowano: 14-11-2015
5. profit

could you give a working example?

§
Napisano: 15-11-2015
Edytowano: 15-11-2015

could you give a working example?

First, something like this https://stackoverflow.com/questions/8022425/getting-blob-data-from-xhr-request

Get the datauri of original image and append it to DOM.

I'm using a different method but same principle.

Then:

////Add base64 img to DOM Then:
var newimg = "Selector of base64 img";
        var canvas = document.createElement("canvas");
        canvas.width = newimage.naturalWidth;
        canvas.height = newimage.naturalHeight;
        var ctx = canvas.getContext("2d");
        newimage.addEventListener("load", function () {
            ctx.drawImage(newimage, 0, 0);
            var converturi = canvas.toDataURL("image/"+format desired);
            console.log(converturi);
/// Do something with new uri
        });

You can obviously skip the first step if it is already base64.

Odpowiedz

Zaloguj się, by odpowiedzieć.