Converting SVG To PNG Using C# [closed] - Stack Overflow
Có thể bạn quan tâm
-
- Home
- Questions
- Tags
- Users
- Companies
- Labs
- Jobs
- Discussions
- Collectives
-
Communities for your favorite technologies. Explore all Collectives
- Teams
Ask questions, find answers and collaborate at work with Stack Overflow for Teams.
Try Teams for free Explore Teams - Teams
-
Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about CollectivesTeams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about TeamsGet early access and see previews of new features.
Learn more about Labs Converting SVG to PNG using C# [closed] Ask Question Asked 16 years, 3 months ago Modified 2 years, 3 months ago Viewed 146k times 121 Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 10 years ago.
Improve this questionI've been trying to convert SVG images to PNG using C#, without having to write too much code. Can anyone recommend a library or example code for doing this?
Share Improve this question Follow edited Sep 20, 2008 at 10:22 harriyott asked Sep 12, 2008 at 13:09 harriyottharriyott 10.7k10 gold badges68 silver badges104 bronze badges 2- 1 i found a good and simple library that you can use in c# github.com/ElinamLLC/SharpVectors , it can convert many type of svg to bmp, jpeg or png – Mahdi Commented Jan 7, 2019 at 7:45
- 2 May I say: those solutions are bad, including wkhtml2pdf/wkhtml2image etc. The SVG specification is complex and evolving, so is CSS-styles, and on top of that, it should look the same as in the browser. wkhtml2X, for example, has massive problems with fonts, and the webkit engine inside is just too old. Fortunately, there is a solution: Chrome has headless-mode, and with its Debugging-API, you can get PNG-images and PDFs from Headless-Chrome itselfs, with MasterDevs/ChromeDevTools in C#: Example: github.com/ststeiger/ChromeDevTools/blob/master/source/… – Stefan Steiger Commented Sep 5, 2019 at 6:54
6 Answers
Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 92There is a much easier way using the library http://svg.codeplex.com/ (Newer version @GIT, @NuGet). Here is my code
var byteArray = Encoding.ASCII.GetBytes(svgFileContents); using (var stream = new MemoryStream(byteArray)) { var svgDocument = SvgDocument.Open(stream); var bitmap = svgDocument.Draw(); bitmap.Save(path, ImageFormat.Png); } Share Improve this answer Follow edited Oct 13, 2016 at 8:00 AxelEckenberger 16.9k3 gold badges49 silver badges73 bronze badges answered Oct 14, 2012 at 16:54 AnishAnish 3,1623 gold badges30 silver badges30 bronze badges 9- 1 I had to use the github version because it's more up-to-date and even that does not support the image element. – Brian Herbert Commented Oct 30, 2013 at 10:26
- i'm used from this code, it throws object not set to an instance of an object when want to execute var bitmap = svgDocument.Draw();. what's the problem? – Rasool Ghafari Commented Apr 22, 2015 at 20:53
- @RasoolGhafari make sure your svgDocument is not null. – Anish Commented Apr 23, 2015 at 14:02
- svgDocument is not null. This is some kind of internal problem in the library. – Jonathan Allen Commented Jul 23, 2015 at 2:56
- @JonathanAllen, I was answering Rasool's comment. – Anish Commented Jul 23, 2015 at 13:45
You can call the command-line version of inkscape to do this:
http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx
Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:
Original Project http://www.codeplex.com/svg
Fork with fixes and more activity: (added 7/2013) https://github.com/vvvv/SVG
Share Improve this answer Follow edited Nov 13, 2013 at 10:59 harriyott 10.7k10 gold badges68 silver badges104 bronze badges answered Sep 12, 2008 at 13:11 EspoEspo 41.9k21 gold badges136 silver badges161 bronze badges 11- 39 Thanks Espo. I actually wrote that inkscape blog post! Although it "works", it's not a particularly robust solution. I like the codeplex project though - I'll give it a look. Thanks. – harriyott Commented Sep 12, 2008 at 13:16
- 9 How embarrassing :) Good thing maybe the SVG rendering engine could help you out though. – Espo Commented Sep 12, 2008 at 13:19
- 21 I take it as a compliment. I've not been quoted to myself before! – harriyott Commented Sep 12, 2008 at 13:36
- have u tried the svg rendering engine? can u share ur solution plz. im trying to make it work but having troubles,see here – Armance Commented Dec 8, 2011 at 10:01
- 1 I have tried github.com/vvvv/SVG and it works but with certain limitations. The image element has not been implemented - I checked the source code. @FrankHale I had to remove an xmlns from the svg because raphael added it twice. – Brian Herbert Commented Oct 30, 2013 at 10:24
When I had to rasterize svgs on the server, I ended up using P/Invoke to call librsvg functions (you can get the dlls from a windows version of the GIMP image editing program).
[DllImport("kernel32.dll", SetLastError = true)] static extern bool SetDllDirectory(string pathname); [DllImport("libgobject-2.0-0.dll", SetLastError = true)] static extern void g_type_init(); [DllImport("librsvg-2-2.dll", SetLastError = true)] static extern IntPtr rsvg_pixbuf_from_file_at_size(string file_name, int width, int height, out IntPtr error); [DllImport("libgdk_pixbuf-2.0-0.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] static extern bool gdk_pixbuf_save(IntPtr pixbuf, string filename, string type, out IntPtr error, __arglist); public static void RasterizeSvg(string inputFileName, string outputFileName) { bool callSuccessful = SetDllDirectory("C:\\Program Files\\GIMP-2.0\\bin"); if (!callSuccessful) { throw new Exception("Could not set DLL directory"); } g_type_init(); IntPtr error; IntPtr result = rsvg_pixbuf_from_file_at_size(inputFileName, -1, -1, out error); if (error != IntPtr.Zero) { throw new Exception(Marshal.ReadInt32(error).ToString()); } callSuccessful = gdk_pixbuf_save(result, outputFileName, "png", out error, __arglist(null)); if (!callSuccessful) { throw new Exception(error.ToInt32().ToString()); } } Share Improve this answer Follow edited May 4, 2016 at 10:49 Uwe Keim 40.7k61 gold badges185 silver badges301 bronze badges answered Aug 9, 2011 at 22:25 nw.nw. 5,1358 gold badges38 silver badges44 bronze badges 1- 1 librSVG is not bad, but fonts/text, it doesn't handle them correctly. Instead, take a look at headless-chrome, chrome-debugging API, and a C# API for the chrome-debugging API: github.com/ststeiger/ChromeDevTools/blob/master/source/… – Stefan Steiger Commented Sep 5, 2019 at 7:04
I'm using Batik for this. Batik is a graphics library written in Java, with a command line interface. This makes that you can Batik from C#, same as the following example in Delphi:
procedure ExecNewProcess(ProgramName : String; Wait: Boolean); var StartInfo : TStartupInfo; ProcInfo : TProcessInformation; CreateOK : Boolean; begin FillChar(StartInfo, SizeOf(TStartupInfo), #0); FillChar(ProcInfo, SizeOf(TProcessInformation), #0); StartInfo.cb := SizeOf(TStartupInfo); CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False, CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, StartInfo, ProcInfo); if CreateOK then begin //may or may not be needed. Usually wait for child processes if Wait then WaitForSingleObject(ProcInfo.hProcess, INFINITE); end else ShowMessage('Unable to run ' + ProgramName); CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end; procedure ConvertSVGtoPNG(aFilename: String); const ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar '; begin ExecNewProcess(ExecLine + aFilename, True); end; Share Improve this answer Follow edited Aug 24, 2022 at 16:19 answered Feb 14, 2009 at 5:34 stevenvhstevenvh 3,1619 gold badges45 silver badges56 bronze badges 4- @downvoters - Please explain why you downvote. A downvote without an explanation has zero value. – stevenvh Commented Sep 19, 2016 at 10:11
- 7 i guess downvotes come from the question text which contain "c#" in it. and your proposal is delphi – Denis Commented Sep 20, 2017 at 13:56
- 1 didn't downvote, but you could edit your answer and make it clear that Batik is a Java library that you could call from C# or whatever language (in this case you showed how to call it in Delphi) – ErrCode Commented Aug 23, 2018 at 17:16
- 1 Starting a new process is slow. Also, how correctly does batik rasterize ? Latest binaries are hard to get. Instead of putting up with that crap, take a look at headless-chrome, chrome-debugging API, and a C# API for the chrome-debugging API: github.com/ststeiger/ChromeDevTools/blob/master/source/… - For all Java-users, I'm sure there's also Java-API's around chrome's debugging-API. – Stefan Steiger Commented Sep 5, 2019 at 7:06
To add to the response from @Anish, if you are having issues with not seeing the text when exporting the SVG to an image, you can create a recursive function to loop through the children of the SVGDocument, try to cast it to a SvgText if possible (add your own error checking) and set the font family and style.
foreach(var child in svgDocument.Children) { SetFont(child); } public void SetFont(SvgElement element) { foreach(var child in element.Children) { SetFont(child); //Call this function again with the child, this will loop //until the element has no more children } try { var svgText = (SvgText)parent; //try to cast the element as a SvgText //if it succeeds you can modify the font svgText.Font = new Font("Arial", 12.0f); svgText.FontSize = new SvgUnit(12.0f); } catch { } }Let me know if there are questions.
Share Improve this answer Follow answered Feb 14, 2013 at 16:04 Michal KielochMichal Kieloch 516 bronze badges 2- parent is not defined in SetFont, should be element or rename the element variable to parent at the function signature – Norbert Kardos Commented Jan 8, 2019 at 10:11
- Also Font seems to be a string now. However this was a lifesaver, thanks! – Norbert Kardos Commented Jan 8, 2019 at 10:27
you can use altsoft xml2pdf lib for this
Share Improve this answer Follow answered Feb 24, 2009 at 21:45 lostlost Add a comment |Not the answer you're looking for? Browse other questions tagged
or ask your own question.- The Overflow Blog
- Why do developers love clean code but hate writing documentation?
- This developer tool is 40 years old: can it be improved?
- Featured on Meta
- The December 2024 Community Asks Sprint has been moved to March 2025 (and...
- Stack Overflow Jobs is expanding to more countries
Linked
32 How to open and render SVG files in .NET environment? 10 Convert SVG to PNG or JPEG 6 convert svg to image programmatically 3 How to convert SVG images for use with Pisa / XHTML2PDF? 3 Which C# library allows reliable SVG to PDF conversion? 1 Converting SVG image from Url to PNG in C# 1 From URI to Image in .NET 2 SVG Rendering Engine DLL & iTextSharp.text.Image - Convert image svg taken by url 1 adding a google visualization areachart svg to a pdf using ITextSharp 0 How can I save a data:image/svg+xml;utf8 image as a valid image file using C#? See more linked questionsRelated
621 How to convert a SVG to a PNG with ImageMagick? 1419 How and when to use ‘async’ and ‘await’ 1908 Proper use of the IDisposable interface 1025 What is the difference between .NET Core and .NET Standard Class Library project types? 1870 Is there a reason for C#'s reuse of the variable in a foreach? 968 Reading settings from app.config or web.config in .NET 471 How to change color of SVG image using CSS (jQuery SVG image replacement)? 2427 Should 'using' directives be inside or outside the namespace in C#? 1736 Why not inherit from List<T>? 517 SVG drop shadow using css3Hot Network Questions
- Meaning of Second line of Shakespeare's Sonnet 66
- How does Christine's origin differ in the movie rather than the book?
- Does Helldivers 2 still require a PSN account link on PC (Steam)?
- Is it important that my dishwasher's cabinet seals make contact with the opening?
- What network am I connected to and what is Air OS?
- Example of a finitely generated metabelian group whose Fitting subgroup is not nilpotent
- Errors while starting vite + react
- why would a search warrant say that the items to search for were the following: hair, fibers, clothing, rope wire, and binding material?
- How to Speed Up the Summation of a Sequence?
- An extension of Lehmer's conjecture on Ramanujan's tau function
- Can Bob send a stone into Alice's future?
- Would reflected sunlight suffice to read a book on the surface of the Moon?
- Dehn-twist on punctured 3-manifold
- Why is Jesus called Prince of Peace and not King of Peace considering he was also called Eternal Father?
- Is pragmatism a theory of epistemology? What are its tenets?
- how to increase precision when using the fpu library?
- What abbreviation for knots do pilots in non-English-speaking countries use?
- Why is the spectrum of the Laplacian on the torus discrete?
- What are "rent and waistline parties"?
- Is it damaging to have a Withdraw on a continuing education transcript when applying to PhD program?
- Where does this whitespace above my faded TikZ image come from?
- How to Mitigate Risks Before Delivering a Project with Limited Testing?
- Removing Matching Pixels?
- Does `autoclean-once` without vacuuming lightningd.sqlite3 slow down the future growth of size lightningd.sqlite3?
Từ khóa » Svg To Png C#
-
C# Convert SVG To PNG, JPEG, BMP, TIFF, GIF - Aspose Blog
-
Convert SVG To PNG | C# | Documentation
-
[Fork] Convert SVG To PNG Using NuGet Package Svg -.NET Fiddle
-
Convert SVG Files To PNG Or JPEG Using .NET - Meziantou's Blog
-
Converting Svg File To Image - MSDN - Microsoft
-
Star - Discover Gists · GitHub
-
How To Convert SVG To PNG In C# | SVG To PNG Online
-
How To Convert SVG To PNG | Telerik Reporting
-
Svg To Image Converter Using C# .NET - YouTube
-
Convert SVG To PNG Or JPEG Using C# In ASP.Net - ASPsnippets
-
C# Program To Convert SVG Image To PNG ... - Coding Diksha
-
C# Program To Convert SVG Image To PNG Converter GUI Desktop ...
-
SVG To PNG Converter In C# - Conversion - GroupDocs
-
Converting SVG To PNG Using C# - Newbedev