Skip to content

Data-URI doesn't handle URI-encoding (percent-escaping) #2126

Open

Description

@josephrexme

Steps to Reproduce

Based on the documentation showing support for data URI in the following syntax

var Canvas = require('canvas');
var canvas = Canvas.createCanvas(200, 200);
var ctx = canvas.getContext('2d');

const img = new Image()
img.onload = () => ctx.drawImage(img, 0, 0)
img.onerror = err => { throw err }

img.src = SOME_DATA_URI

I had passed the following valid SVG data-uri

data:image/svg+xml;charset=utf-8,%3Csvg aria-hidden='true' focusable=
'false' data-prefix='fas' data-icon='envelope-open' class='svg-inline--fa fa-env
elope-open fa-w-16' role='img' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 5
12 512' style='color: %23ff00ff%3Bbox-sizing: border-box%3Bwidth: 600%3Bheight:
600%3Bpadding: 24px%3Bbackground-color: %23000000%3Bborder-radius: 10px%3B'%3E%3
Cpath fill='currentColor' d='M512 464c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.4
9-48-48V200.724a48 48 0 0 1 18.387-37.776c24.913-19.529 45.501-35.365 164.2-121.
511C199.412 29.17 232.797-.347 256 .003c23.198-.354 56.596 29.172 73.413 41.433
118.687 86.137 139.303 101.995 164.2 121.512A48 48 0 0 1 512 200.724V464zm-65.66
6-196.605c-2.563-3.728-7.7-4.595-11.339-1.907-22.845 16.873-55.462 40.705-105.58
2 77.079-16.825 12.266-50.21 41.781-73.413 41.43-23.211.344-56.559-29.143-73.413
-41.43-50.114-36.37-82.734-60.204-105.582-77.079-3.639-2.688-8.776-1.821-11.339
1.907l-9.072 13.196a7.998 7.998 0 0 0 1.839 10.967c22.887 16.899 55.454 40.69 10
5.303 76.868 20.274 14.781 56.524 47.813 92.264 47.573 35.724.242 71.961-32.771
92.263-47.573 49.85-36.179 82.418-59.97 105.303-76.868a7.998 7.998 0 0 0 1.839-1
0.967l-9.071-13.196z'%3E%3C/path%3E%3C/svg%3E

and gotten image error Error: Unsupported image type at setSource.

Here's a demo on codesandbox: https://codesandbox.io/s/eloquent-noether-byf8wm

What will it take to support this? I'll be happy to help where needed with code or sponsor contribution.

I intially included this as a comment in #1709 but thought it might need its own issue.

Activity

  1. LinusU commented on Oct 11, 2022

    @LinusU
    Collaborator

    @josephrexme there is a test case covering this:

    it('loads SVG data URL utf8', function () {
    if (!HAVE_SVG) this.skip()
    const utf8Encoded = fs.readFileSync(svgTree, 'utf8')
    const dataURL = `data:image/svg+xml;utf8,${utf8Encoded}`
    return loadImage(dataURL).then((img) => {
    assert.strictEqual(img.onerror, null)
    assert.strictEqual(img.onload, null)
    assert.strictEqual(img.width, 200)
    assert.strictEqual(img.height, 200)
    assert.strictEqual(img.complete, true)
    })
    })

    Could it be that your build of Canvas doesn't include SVG support at all? That would happen if librsvg wasn't found when building.

    Could you try and run this command and paste its output:

    node -p 'require("canvas").rsvgVersion'
  2. josephrexme commented on Oct 11, 2022

    @josephrexme
    Author

    @LinusU thanks for your response. I got 2.50.5 after running the command

  3. josephrexme commented on Oct 11, 2022

    @josephrexme
    Author

    So I investigated this further after looking at the test case shared. It turned out that I was running encodeURIComponent on the SVG first which I usually do for SVG data-uri on the web, but node-canvas didn't like that. It worked without doing any prior encoding. Thanks @LinusU

  4. LinusU commented on Oct 12, 2022

    @LinusU
    Collaborator

    Hmm, this is interesting. We aim to be as compatible with the web as possible, so we should probably be doing decodeURI or decodeURIComponent in our code 🤔

    Opening this again with a slightly changed title.

  5. reopened this on Oct 12, 2022
  6. changed the title [-]Support for SVG data-URI with Image()[/-] [+]Data-URI doesn't handle URI-encoding (percent-escaping)[/+] on Oct 12, 2022
  7. zbjornson commented on Oct 22, 2022

    @zbjornson
    Collaborator

    Indeed:

    Without ";base64", the data (as a sequence of octets) is represented using ASCII encoding for octets inside the range of safe URL characters and using the standard %xx hex encoding of URLs for octets outside that range.
    -- https://www.rfc-editor.org/rfc/rfc2397#section-2

  8. flohall commented on Jan 1, 2023

    @flohall

    Hey I have invested quite some time in performance testing for converting svgData into a rasterized image for node-canvas and browser. I recommend to differentiate between browser and node-canvas to get the maximum performance.
    Why does it even matter? For our software we use 1000s of different svgs over different frames extracted from lottie files and manipulated with additional CSS to color specific svg elements by classes. So svg creation speed is super crucial for us.

    Ideal Solution

    This is my ideal solution, but needs differentiation between browser and node-canvas. I haven't came across any svg that needed more than # to be replaced. And I have tested quite some. But maybe there are more characters.

    /**
     * Returns serialized SVG source.
     */
    private static getSerializedSvgSrc(svgString, isBrowser: boolean): string | Buffer {
        // This is way faster than base64 encoding.
        // svgString.replace(/#/g, "%23") is additionally around 30 times faster than encodeURIComponent(svgString).
        if (isBrowser) {
            return 'data:image/svg+xml;utf8,' + svgString.replace(/#/g, "%23");
        } else {
            return Buffer.from(svgString, 'utf-8');
        }
    }
    

    Alternatives

    By the way the fastest conversion to have a valid input for backend would be this here: return 'data:image/svg+xml;utf8,' + svgString, but I have looked into the node-canvas code an the string is later read and then put in a Buffer anyway so its probably faster to put it in the Buffer directly.

    If you just want to have some code that works for browser and node-canvas at the same time you could for example use:

    return 'data:image/svg+xml;utf8,'+ unescape(encodeURIComponent(svgString));
    

    or this should do the job in both environments as well, but faster (also unescape is deprecated):

    return 'data:image/svg+xml;utf8,' + svgString.replace(/#/g, "%23");
    

    Some more options I have compared

    return 'data:image/svg+xml;base64,'+ Buffer.from(svgString, 'utf-8').toString("base64");
    

    vs

    return `data:image/svg+xml;utf8,${svgString}`;
    

    vs

    return  'data:image/svg+xml;utf8,' + svgString;
    

    vs

    return 'data:image/svg+xml;base64,'+ Buffer.from(unescape(encodeURIComponent(svgString)), 'utf-8').toString("base64");
    

    Conclusion

    @LinusU please don't add decodeURIComponent to the canvas code, because it would mean you first have to encode and then decode. Probably meaning to loose 1-2 ms per svg vs. only using a small fraction of a 1 ms. And if you do it anyway at least keep the option to pass the Buffer without the decoding directly. I would prefer, if we instead add some more info to the README file on how to handle svgs.

    Postscript

    By the way the 2.50.5 version of librsvg is crap. It fails to render some svg properties that are supported in later versions. I would recommend to adjust the prebuild binaries to use 2.54.4 or later. This fixed a lot of issues I had with svg rendering. See here for an OS supporting this version: https://repology.org/project/librsvg/versions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions