C# import of Adobe Illustrator (.AI) files render to Bitmap? - c#

Anyone knows how to load a .AI file (Adobe Illustrator) and then rasterize/render the vectors into a Bitmap so I could generate eg. a JPG or PNG from it?
I would like to produce thumbnails + render the big version with transparent background in PNG if possible.
Ofcause its "possible" if you know the specs of the .AI, but has anyone any knowledge or code to share for a start? or perhaps just a link to some components?
C# .NET please :o)
Code is most interesting as I know nothing about reading vector points and drawing splines.

Well, if Gregory is right that ai files are pdf-compatible, and you are okay with using GPL code, there is a project called GhostscriptSharp on github that is a .NET interface to the Ghostscript engine that can render PDF.

With the newer AI versions, you should be able to convert from PDF to image. There are plenty of libraries that do this that are cheap, so I would choose buy over build on this one. If you need to convert the older AI files, all bets are off. I am not sure what format they were in.

private void btnGetAIThumb_Click(object sender, EventArgs e)
{
Illustrator.Application app = new Illustrator.Application();
Illustrator.Document doc = app.Open(#"F:/AI_Prog/2009Calendar.ai", Illustrator.AiDocumentColorSpace.aiDocumentRGBColor, null);
doc.Export(#"F:/AI_Prog/2009Calendar.png",Illustrator.AiExportType.aiPNG24, null);
doc.Close(Illustrator.AiSaveOptions.aiDoNotSaveChanges);
doc = null; //
}
Illustrator.AiExportType.aiPNG24 can be set as JPEG,GIF,Flash,SVG and Photoshop format.

I Have Tested that with Pdf2Png and it worked fine with both .PDF and .ai files.
But I don't know how it will work with transparents.
string pdf_filename = #"C:\test.ai";
//string pdf_filename = #"C:\test.pdf";
string png_filename = "converted.png";
List<string> errors = cs_pdf_to_image.Pdf2Image.Convert(pdf_filename, png_filename);

Related

How to write and view converted pdfs to and from memory?

Right now I am using ghostscript in Unity to convert pdfs to jpgs and view them in my project.
Currently it flows like so:
-Pdfs are converted into multiple jpegs (one for each page)
-The converted jpegs are written to disk
-They are then read in by bytes into a 2D texture
-And this 2D texture is assigned to a GameObjects RawImage component
This works perfectly in Unity, but... (now comes the hiccup) my project is intended to run on the Microsoft Hololens.
The Hololens runs on the Windows 10 API, but in a limited capacity.
Where the issue arises is when I try to convert pdfs and view them on the Hololens. Quite simply, the Hololens cannot create or delete files outside of its known folders (Pictures, Documents, etc).
My imagined solution to this problem is to instead of write the converted jpeg files to disk, write them to memory and view them from there.
In talking with GhostScript devs, I was told GhostScript.NET does what I am looking to do - convert pdfs and view them from memory (It does this with the Rasterizer/Viewer classes, I believe, but again I don't understand it quite well).
I've been lead to look at the latest GhostScript.NET docs to route out how this is done, but I simply don't understand them well enough to approach this.
My question is then, based on how I'm using ghostscript now, how do I use GhostScript.NET in my project to write the converted jpegs into memory and view them there?
Here's how I'm doing it now (code-wise):
//instantiate
byte[] fileData;
Texture2D tex = null;
//if a PDF file exists at the current head path
if (File.Exists(CurrentHeadPath))
{
//Transform pdf to jpg
PdfToImage.PDFConvert pp = new PDFConvert();
pp.OutputFormat = "jpeg"; //format
pp.JPEGQuality = 100; //100% quality
pp.ResolutionX = 300; //dpi
pp.ResolutionY = 500;
pp.OutputToMultipleFile = true;
CurrentPDFPath = "Data/myFiles/pdfconvimg.jpg";
//this call is what actually converts the pdf to jpeg files
pp.Convert(CurrentHeadPath, CurrentPDFPath);
//this just loads the first image
if (File.Exists("Data/myFiles/pdfconvimg" + 1 + ".jpg"))
{
//reads in the jpeg file by bytes
fileData = File.ReadAllBytes("Data/myFiles/pdfconvimg" + 1 + ".jpg");
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
//Read Texture into RawImage component
PdfObject.GetComponent<RawImage>().texture = tex;
PdfObject.GetComponent<RawImage>().rectTransform.sizeDelta = new Vector2(288, 400);
PdfObject.GetComponent<RawImage>().enabled = true;
}
else
{
Debug.Log("reached eof");
}
}
The convert function is from a script called PDFConvert which I obtained from code project. Specifically How To Convert PDF to Image Using Ghostscript API.
From the GhostScript.Net documentation, take a look at the example code labeled: "Using GhostscriptRasterizer class". Specifically the following lines:
Image img = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
img.Save(pageFilePath, ImageFormat.Png);
The Image class seems to be part of the System.Drawing package, and System.Drawing.Image has another Save method where the first parameter is a System.IO.Stream.

How to convert a png file to .GRF file used for zebra printer

I use Zebraprinter for printing the labels. My printer is 203dpi. For last couple of days i was searching in internet and i found there are Zebraprint utilities.. to convert to DFR format.. which sucks.. they are not fully explaining how to do this.. They just says convert to ~DG format. any print it, which is not happening!!
Rather I would like to convert a png file to a .GRF file and send to the printer for printing.. IS there any deadly available free software in internet which does my needs,
Also, i tired to develop a software which does the job for printing the letters.. which is wiring fine. i don't know how to print pictures using this printer.
I need to convert this image https://imageshack.com/i/pb0BArbep to .GRF format. How can i do all this under a single button press.. Any helps..
Thanks a lot.
Code snippet:-
private void button2_Click(object sender, EventArgs e)
{
string s = Print();
PrintFactory.sendTextToLPT1(s);
}
private string Print()
{
string s = "";
s += "^XA^LH"+ text.textbox + ".GRF,1,1^FS";
s += "^FO250,294^FD^FS";
s += "^XZ";
return s;
}
It's been a month since this was asked, so I don't know if an answer is still needed or not, but I'll have a go at it. I've actually been doing a lot of research on ZPL lately, (one of the reasons I came across this question), and I had to do something similar. With a 203 dpi printer as well, actually. I'm not sure how to convert a PNG to GRF, but I was able to print out a graphic using just a PNG:
^XA
^MNY
^LL203
~DYE:{name},P,P,{file size},,{data}
^XZ
The ^MN has to do with Media Tracking, and you may have to change it a bit to suit your needs, depending on the label. Same thing with ^LL, which specifies the label length. For an 8 dots/mm (203 dpi), the value you use as an argument is calculated by 203.2 * length of label in inches. After that, there's a few values to plug into ~DY (Download graphics, page 112 on the manual), the first of which is the name you want to use to reference the file. I didn't add a file extension, as the printer seemed to do that for me, since I specified it was a PNG in the arguments. The second is the size, in bytes, of the PNG file. And lastly, the actual data from the file in the form of ASCII hex. Now with the file being saved on the printer, I was then able to print the graphic in a script using:
^IME:{name}.PNG
^FS
Note: After uploading the file to the printer, I was able to confirm it did save as a PNG file by connecting to the printer VIA IP in a browser and going to "Directory Listing". I'm not sure if all those printers have this feature, but the one I used did. If it does, you can use this to confirm that the file properly uploaded. (It should be in Onboard Flash)
Hope this helps!
The manual I used is here.
I also came across numerous other StackOverflow questions that helped out a bit, and a few threads on other forums. One question that was also in C# that helped me quite a bit can be found here.

Cannot find a way to make tessnet2 work

I have created a console application.
Added a reference to tessnet2_32.
Ocr ocr = new Ocr();
using (Bitmap bmp = new Bitmap(filename))
{
tessnet2.Tesseract tessocr = new tessnet2.Tesseract();
tessocr.Init(#"C:\temp\tessdata", "eng", false);
...
I also tried changing "C:\temp\tessdata" to
C:\work\ConsoleApplication3\ConsoleApplication3
C:\work\ConsoleApplication3\ConsoleApplication3\tessdata
C:\work\ConsoleApplication3\ConsoleApplication3\bin\debug
C:\work\ConsoleApplication3\ConsoleApplication3\bin
C:\work\ConsoleApplication3\ConsoleApplication3\bin\debug\tessdata
C:\work\ConsoleApplication3\ConsoleApplication3\bin\tessdata
C:\work\ConsoleApplication3\ConsoleApplication3\debug\tessdata
C:\work\ConsoleApplication3\tessdata
C:\work\ConsoleApplication3\
The tessdata folder itself contained 9 failed and was added to all of these locations:
eng.cube.bigrams
eng.cube.fold
eng.cube.lm
eng.cube.bigrams
eng.cube.params
eng.cube.size
eng.cube.word-freq
eng.tesseract_cube.nn
eng.traineddata
But it just always exists at that .Init line with a message:
The file 'z:\dev\interne\cs\tesseract-ocr-svn\dotnet\tessnet2.cpp' does not exist.
I cannot imagine why it is trying to access some Z disk while I only have C. Or I just completely misunderstand the error.
Can someone be kind enough to post step by step telling what to do and/or what I am doing wrong? I feel completely lost even after reading 30+ google links.
You use the wrong version of language data file; what you have is for Tesseract 3.0x. tessnet2 is .NET wrapper for Tesseract 2.04, so you will need to load compatible data file.
Try download tesseract-2.00.eng.tar.gz from https://sourceforge.net/projects/tesseract-ocr-alt/files/.

How to extract layers from a Photoshop file? C#

Is there a library in C# that will allow me to read the layers in a photoshop file (PSD) and extract them as transparent images (PNG)?
Photoshop has a batch command that will extract all layers in individual files but there is no choice of transparent PNGs. My goal is to create a small utility program that will create combinations of layers as you like (for example think of creating a card deck).
There's a nice article on CodeProject which might be helpful. And here's a thread on SO discussing PSD file format parsing with C#.
I couldnt find much on this anywhere, but this is how i ended up doing it.
using Photoshop;
Photoshop.PsdFile psd = new Photoshop.PsdFile();
psd.Load(pingTextsPsd);
for (int j = 0; j < psd.Layers.Count; j++)
{
System.Drawing.Image myPsdImage = ImageDecoder.DecodeImage(psd.Layers[j]);
myPsdImage.Save(pingsOutputPath + psd.Layers[j].Name + ".png");
}
i had to downloaded the cs files that Mr Frank Blumenberg did (based on the Endogine engine by Jonas Beckeman), as getting the paintdotnet dll itself wasnt enough.
I believe it was here that i got the cs files.
http://code.google.com/p/skimpt/source/browse/trunk/Skimpt3/Skimpt3/classes/photoshop/?r=72
This should allow you to get the layers..
:-)
This seems to work fine with CS6 files too.
update: a vs2013 website is here: http://goo.gl/H6nWSN.
You can do that with Photoshop COM.
ImagicMagick (which was mentioned in the other SO article) does allow layers to be extracted separately. See: http://www.rubblewebs.co.uk/imagemagick/psd.php
You can try this for yourself using the command line tool:
convert boots.psd[0] -thumbnail 340x340 boots_png.png
I found a code sample that does this in Java.
"Supports uncompressed or RLE-compressed RGB files only"
Also supports only older PSD versions :
"Does not support additional features in PS versions higher than 3.0"
Also ImageMagick handles PSD and has interfaces to many languages :
"Choose from these interfaces: G2F (Ada), MagickCore (C), MagickWand (C), ChMagick (Ch), ImageMagickObject (COM+), Magick++ (C++), JMagick (Java), L-Magick (Lisp), NMagick (Neko/Haxe), MagickNet (.NET), PascalMagick (Pascal), PerlMagick (Perl), MagickWand for PHP (PHP), IMagick (PHP), PythonMagick (Python), RMagick (Ruby), or TclMagick (Tcl/TK)"
If you don't have Photoshop installed, then you may want to look at the code at http://frankblumenberg.de/doku/doku.php?id=paintnet:psdplugin for more sample code that loads PSD files.
Unfortunately, I don't know of a pre-existing PNG library that does what you want but the canonical library code for PNG file manipulation is located at http://www.libpng.org/pub/png/.

Reading PSD file format

I wonder if this is even possible. I have an application that adds a context menu when you right click a file. It all works fine but here is what I'd like to do:
If the file is a PSD then I want the program to extract the image. Is this possible to do without having Photoshop installed?
Basically I want the user to right click and click "image" which would save a .jpg of the file for them.
edit: will be using c#
Thanks
The ImageMagick libraries (which provide bindings for C#) also support the PSD format. They might be easier to get started with than getting into the Paint.NET code and also come with a quite free (BSD-like) license.
A simple sample (found at http://midimick.com/magicknet/magickDoc.html) using MagickNet would look like this:
using System;
static void Main(string[] args)
{
MagickNet.Magick.Init();
MagicNet.Image img = new MagicNet.Image("file.psd");
img.Resize(System.Drawing.Size(100,100));
img.Write("newFile.png");
MagickNet.Magick.Term();
}
Note: MagickNet has moved to http://www.codeproject.com/KB/dotnet/ImageMagick_in_VBNET.aspx
Well, there's a PSD plugin for Paint.NET which I think is Open-Source which you might want to take a look at for starters:
http://frankblumenberg.de/doku/doku.php?id=paintnet:psdplugin#download
This guy do it easier:
http://www.codeproject.com/KB/graphics/simplepsd.aspx
With a C# library and a sample project.
I've tried with PS2 files and works ok.
I have written a PSD parser which extracts raster format layers from all versions of PSD and PSB. http://www.telegraphics.com.au/svn/psdparse/trunk
You can use GroupDocs.Viewer for .NET API to render your PSD files as images (JPG, PNG, BMP) in your application using a few lines of code.
C#
ViewerConfig config = new ViewerConfig();
config.StoragePath = "D:\\storage\\";
// Create handler
ViewerImageHandler imageHandler = new ViewerImageHandler(config);
// Guid implies that unique document name
string guid = "sample.psd";
// Get document pages as images
List<PageImage> pages = imageHandler.GetPages(guid);
foreach (PageImage page in pages)
{
// Access each image using page.Stream
}
For more details and sample code, please visit here.
Disclosure: I work as a Developer Evangelist at GroupDocs.
For people who are reading this now: the link from accepted answer doesn't seem to work anymore (at least for me). Would add a comment there, but not allowed to comment yet - hence I'm adding a new answer.
The working link where you can find the psdplugin code for Paint.Net: https://github.com/PsdPlugin/PsdPlugin
Here is my own psd parser and exporter:
http://papirosnik.info/psdsplit/.
It allows to correctly parse psd with rgb color 8, 16- and 32-bit for channel, process user masks, export selected layers into jpeg, png, jng, bmp, tiff; create xml layout of exported layers and groups and also create a texture atlas and animations set from given layers.
It's entirely written in C#. If you want its sources inform me via support link on About dialog in the application.
ImageMagick.NET - http://imagemagick.codeplex.com/ - is the later version of the link 0xA3 gave, with some slightly different syntax. (Note, this is untested):
using ImageMagickNET;
public void Test() {
MagickNet.InitializeMagick();
ImageMagickNET.Image img = new ImageMagickNET.Image("file.psd");
img.Resize(new Geometry(100, 100, 0, 0, false, false);
img.Write("newFile.png");
}
I got extraction from psd working. see my answer here
How to extract layers from a Photoshop file? C#
may help someone else.
FastStone does this pretty efficiently.
They do not have their libraries availaible, but I guess you can contact them and see if they can help.
Check out their website: http://www.faststone.org/download.htm
I've had great success with Aspose's Imaging component which can load and save PSD files without Photoshop: https://products.aspose.com/imaging/net

Categories