rich icon indicating copy to clipboard operation
rich copied to clipboard

[REQUEST] Add ability to get SVG image size from SVG XML data

Open jeremyschulman opened this issue 3 years ago • 4 comments

Have you checked the issues for a similar suggestions? Yes

How would you improve Rich?

As a Developer of applications where I want to display "pretty-tables" as image files I need a way to know the exact size of the SVG image for image processing purposes. As a current user of Rich I can extract this information from the SVG XML content produced from Console.export_svg; but it requires intimate internal knowledge of how Rich stores this information. For example use in a 3rd-party package, see: https://github.com/jeremyschulman/rich-consoleimager/blob/main/rich_consoleimager/console.py#L56

As a feature request could you please add a means in Rich so that the library will return the SVG image size? Thank you!

jeremyschulman avatar Jul 31 '22 20:07 jeremyschulman

Hey Jeremy, taking a look at this! I agree that relying on the outermost rect in the SVG to extract the width and height could potentially end up being unreliable if the SVG format changes.

Do you have any ideas or suggestions for what API you'd like Rich to offer to get the width and height of the SVG?

jslvtr avatar Aug 04 '22 08:08 jslvtr

@jslvtr - thank you for looking at this request. I have a few ideas. The first would be to enhance Console.measure() to accept and process the SVG content:

https://rich.readthedocs.io/en/stable/reference/console.html#rich.console.Console.measure

Indicates the first parameter the first parameter could be a string. In this case the string is the SVG content. The method would need to examine the string to see that it was an SVG.

What do you think of this approach?

jeremyschulman avatar Aug 04 '22 12:08 jeremyschulman

I've also found that this extraction is more accurate:

  svg_xml = ETree.fromstring(svg_content)
  _, _, width, height = svg_xml.attrib['viewBox'].split()
  width, height = int(float(width)), int(float(height))

jeremyschulman avatar Aug 04 '22 13:08 jeremyschulman

Thank you @jeremyschulman! Unfortunately Console.measure is used to measure elements within the console, so it wouldn't be suitable for measuring something so different like an SVG. I do agree with you that using the viewBox is more accurate, so what we might do is offer a method of Console that gives you the SVG code as well as the width and height that we use to generate the viewBox.

I'll get a PR ready!

jslvtr avatar Aug 04 '22 14:08 jslvtr