How to extract layers from a Photoshop file? C# - 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/.

Related

JPEG decoder for .NET Core

there is currently no "built in" JPEG decoder class for .NET Core since System.Drawing (except for System.Drawing.Primitives) is currently not present as a nuget package.
I do understand that System.Drawing relies on underlying Win32 GDI code which obviously is not present on all platforms.
I did read some posts about possible implementations and there appear to be some alpha-grade JPEG packages on nuget but I haven't been able to find a proper one.
Does anyone know about a simple way of DECODING JPEG pictures on .NET Core for some server side processing? I don't even need resize or other functions, decoding would suffice perfectly.
Help is greatly appreciated.
Thanks in advance!
-Simon
Have a look at https://github.com/JimBobSquarePants/ImageSharp
With a usage like in these samples:
Sample 1:
// resizing and filter (grayscale)
using (FileStream stream = File.OpenRead("foo.jpg"))
using (FileStream output = File.OpenWrite("bar.jpg"))
{
Image image = new Image(stream);
image.Resize(image.Width / 2, image.Height / 2)
.Grayscale()
.Save(output);
}
Sample 2: Accessing Pixels
Image image = new Image(400, 400);
using (PixelAccessor<Color, uint> pixels = image.Lock())
{
pixels[200, 200] = Color.White;
}
There is an ImageMagick wrapper for .net which looks like it now supports .Net Core: https://magick.codeplex.com
I have also found the following which works like a charm and is extremely slim: https://www.nuget.org/packages/BitMiracle.LibJpeg.NET/

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

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);

Convert PDF to JPG or PNG using C# or Command Line [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I need to convert a PDF file to images. I used for testing purposes "Total PDF Converter" which offers a command line, but it's shareware and I need to find a free alternative.
Does anyone knows such a tool or maybe even a free C# library?
The convert tool (or magick since version 7) from the ImageMagick bundle can do this (and a whole lot more).
In its simplest form, it's just
convert myfile.pdf myfile.png
or
magick myfile.pdf myfile.png
As a GhostScript answer is missing and there is no hint for multipage PDF export yet I think adding another variant is ok.
gs -dBATCH -dNOPAUSE -sDEVICE=pnggray -r300 -dUseCropBox -sOutputFile=item-%03d.png examples.pdf
Options description:
dBatch and dNOPAUSE just tell gs to run in batch mode, which means
more or less it will not ask any questions. Those parameters are also
important if you want to run the command in a bash script.
sDEVICE tells gs what output format to produce. pnggray is for
grayscale, png16m for 24-bit RGB color. If you insist on creating
Jpegs use -sDEVICE=jpeg to produce color JPEG files. Use the -dJPEGQ=N (N is an integer from 0 to 100, default 75)
parameter to control the Jpgeg quality.
-r300 sets the scan resolution to 300dpi. If you prefer a smaller
output sizes use -r70 or if you input pdf has a high resoultion use
-r600. If you have a PDF with 300dpi and specify -r600 your images will be upscaled.
-dUseCropBox tell gs to use a CropBox if defined. A CropBox is
specifies an area of interest on a page. If you have a pdf with a
large white margin and you don't want this margin on your output this
option might help.
-sOutputFile defines the name(s) of the output file. The %03d.png part
tells gs to include a counter for multiple files. A two page pdf
would result in two files named item-001.png and item-002.png.
The last (unnamed parameter is the input file.)
Availability:
The convert command of imagemagick does use the gs command internally. If you can convert a pdf with imagemagick, you already have gs installed.
Install ghostscript:
RHEL:
yum install ghostscript
SLES:
zypper install ghostscript
Debian/Ubuntu:
sudo apt-get install ghostscript
Windows:
You can find Windows binaries under http://www.ghostscript.com/download/gsdnld.html
I have found this solution which worked for me: https://github.com/jhabjan/Ghostscript.NET. It is also available as an nuget download.
Here is the sample code for converting all pdf pages into png images:
private static void Test()
{
var localGhostscriptDll = Path.Combine(Environment.CurrentDirectory, "gsdll64.dll");
var localDllInfo = new GhostscriptVersionInfo(localGhostscriptDll);
int desired_x_dpi = 96;
int desired_y_dpi = 96;
string inputPdfPath = "test.pdf";
string outputPath = Environment.CurrentDirectory;
GhostscriptRasterizer _rasterizer = new GhostscriptRasterizer();
_rasterizer.Open(inputPdfPath, localDllInfo, false);
for (int pageNumber = 1; pageNumber <= _rasterizer.PageCount; pageNumber++)
{
string pageFilePath = Path.Combine(outputPath, "Page-" + pageNumber.ToString() + ".png");
Image img = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
img.Save(pageFilePath, ImageFormat.Png);
}
_rasterizer.Close();
}
The #Thomas answer didn't work in my case.
I gues that works only if you have images in your pdf.
In my case what worked was pdftoppm (source from https://askubuntu.com/a/50180/37527):
pdftoppm input.pdf outputname -png
This will output each page in the PDF using the format outputname-01.png, with 01 being the index of the page.
Converting a single page of the PDF
pdftoppm input.pdf outputname -png -f {page} -singlefile
Change {page} to the page number. It's indexed at 1, so -f 1 would be the first page.
Specifying the converted image's resolution
The default resolution for this command is 150 DPI. Increasing it will result in both a larger file size and more detail.
To increase the resolution of the converted PDF, add the options -rx {resolution} and -ry {resolution}. For example:
pdftoppm input.pdf outputname -png -rx 300 -ry 300
You may want to check this free solution
http://www.codeproject.com/Articles/32274/How-To-Convert-PDF-to-Image-Using-Ghostscript-API
It easily convert PDF to images (single file or multiple files)
is open source, and use ghostscript (free download)
Example of its use:
converter = new PDFConverter();
converter.JPEGQuality = 90;
converter.OutputFormat = "jpg";
string output = "output.jpg";
converter.Convert("input.pdf", output);
You should use iText sharp. Its a port of an open source java project for manipulating PDFs.
http://sourceforge.net/projects/itextsharp/
2JPEG command line tool can do it, like:
2jpeg.exe -src "C:\In\*.pdf" -dst "C:\Out"

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

How do I get a Video Thumbnail in .Net?

I'm looking to implement a function that retrieves a single frame from an input video, so I can use it as a thumbnail.
Something along these lines should work:
// filename examples: "test.avi", "test.dvr-ms"
// position is from 0 to 100 percent (0.0 to 1.0)
// returns a bitmap
byte[] GetVideoThumbnail(string filename, float position)
{
}
Does anyone know how to do this in .Net 3.0?
The correct solution will be the "best" implementation of this function.
Bonus points for avoiding selection of blank frames.
I ended up rolling my own stand alone class (with the single method I described), the source can be viewed here. Media browser is GPL but I am happy for the code I wrote for that file to be Public Domain. Keep in mind it uses interop from the directshow.net project so you will have to clear that portion of the code with them.
This class will not work for DVR-MS files, you need to inject a direct show filter for those.
This project will do the trick for AVIs: http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx
Anything other formats, you might look into directshow. There are a few projects that might help:
http://sourceforge.net/projects/directshownet/
http://code.google.com/p/slimdx/
1- Get latest version of ffmpeg.exe from : http://ffmpeg.arrozcru.org/builds/
2- Extract the file and copy ffmpeg.exe to your website
3- Use this Code:
Process ffmpeg;
string video;
string thumb;
video = Server.MapPath("first.avi");
thumb = Server.MapPath("frame.jpg");
ffmpeg = new Process();
ffmpeg.StartInfo.Arguments = " -i "+video+" -ss 00:00:07 -vframes 1 -f image2 -vcodec mjpeg "+thumb;
ffmpeg.StartInfo.FileName = Server.MapPath("ffmpeg.exe");
ffmpeg.Start();
There are some libraries at www.mitov.com that may help. It's a generic wrapper for Directshow functionality, and I think one of the demos shows how to take a frame from a video file.
This is also worth to see:
http://www.codeproject.com/Articles/13237/Extract-Frames-from-Video-Files

Categories