Photoshop file format importer / parser in flash AS3

August 11th, 2010 by Slav

For a recent Flex CMS project I needed PSD importer so I went googling in a hope for a decent PSD parser.  I found only one somewhat usable project which was essenialy a Java port of this parser that imported psd files into flash..

The problem with this parser was in supported only very, basic, plain psd files, and adding anything (like a folder group for example ) would break it. So I decided to write my own one instead.

As you might have heard psd isn’t exactly the easiest format to parse, so rather then starting from the scratch I  based a portion of the code on the Munegon’s parser, also referenced Yet another PSD parser by Jonas Beckeman written in java. Quite helfull was this Python PSD parser and of course an official PSd file format specifications document from Adobe.It was still lot of trial and error, as even official CS format specification docs aren’t complete and contains errors. But at the end I got this :

and this is the same file in Photoshop :

What is currently supported :

PSD FILE :
  • Parsing  canvas width x height
  • parsing file color information (number of color channels, color depth, color mode)
  • parsing file’s composite bitmap snapshot
  • parsing all layers and layer folders
Layers :
  • parsing layer bitmap data
  • parsing layers bounds and position
  • parsing layer name
  • parsing layer ID
  • parsing layer blend mode
  • parsing layer colour channels
  • parsing layer alpha
  • parsing layer filters
  • parsing layer extra  properties such as : isLocked, isVisible, clipping applied
  • parsing layer type (normal, folder)
What is  not supported but planned for the future :
  • layer  masks
  • layer paths
  • layer vector shapes
  • parsing text layers as formatted string
  • parsing layers with zip (with or without prediction) compression
As photshop != flash, there are , and will be some necessary incompatibilities. Although I tried to support all the crossover features, not everything will look the same  after import
here are some gotchas :
  • Layer alpha in flash is layer opacity in Photoshop..Layer Fill values are ignored.
  • Incompatible photoshop layer blend modes are interpreted as Normal blend mode
  • Only 4 filters / layer effects are currently supported (drop shadow , inner drop shadow , glow, inner glow) but even these need to have to be applied with normal blend mode, as flash doesn’t support a filters with a different blend mode as the display object they are applied to. For example it’s perfectly possible to have an photoshop layer in screen mode with drop shadow applied in multiply mode, but it flash you don’t have a blend mode settings for a filter..
  • only layers with RAW or RLE compression are being parsed at the moment.. So if you don’t see the layer bitmap data it’s probably compressed with zip compression.
Note on the layer folders / layer groups :
Layer groups are being parsed and they are also PSDLayer class type.

To identify them you need to check for the layer type:

There are 4 layer types :LayerType_FOLDER_OPEN, LayerType_FOLDER_CLOSED , LayerType_HIDDEN and LayerType_NORMAL.

Layer folder hidden is marker for the end of the layer group. So if you want to parse the folder structure, check where the layer type folder starts and then every layer that follows is inside of that folder, until you reach layer type hidden.

How to use this parser

Very simple.  You just create instance of PSDParser (it is Singleton) and then call “parse” method , passing the content of your psd file in byte array format.

The parsing is synchronous so after that line, you will already have all the file/layers info available..

I’ve made 2 apps that should help you get started.

PSD Viewer is a simple flex app that allows you to load and view psd files and reads the supported layers, while showing their blend modes, visibility , lock, alpha , layer effect etc, in “Photoshop-esque” style. View source is enabled so you can get the source code from here. (If you don’t have the psd file to test use the “testPSD1.psd” file from flex project’s “assets” subfolder).

Simple example is a basic single class as3 app that just loads the psd file and then on click cycles through the layers, bringing the one in the back to the top.

Enjoy!

PS:  As this is still early beta, some PSD files may/will break the parser (especially those with unsupported features (see above) or those not saved in compatibility mode…

Posted in AS3, flash, Flex, Flex 4

32 Responses

  1. FlashPad » Blog Archive » Photoshop file format importer / parser … | photoshop

    […] artykuł: FlashPad » Blog Archive » Photoshop file format importer / parser … a-simple-flex, allows-you, blend, load-and, reads-the-supported, simple-flex, style, supported, […]

  2. baz

    Wow good job, i am sure lots of people will appreciate your hard work.
    congrats ^^

  3. Tweets that mention FlashPad » Blog Archive » Photoshop file format importer / parser in flash AS3 -- Topsy.com

    […] This post was mentioned on Twitter by Slavomir Durej, FMC Washington DC, fmchicago, Photoshop Tutorial, santhosh and others. santhosh said: Photoshop file format importer / parser in flash AS3: For a recent Flex CMS project I needed PSD importer so I … http://durej.com/?p=128 […]

  4. Rumble

    Interesting stuff. Does it handle the layer effects you can add in photoshop, such as drop shadow, outer-glow, color overlay, etc, etc…?

  5. Slav

    Rumble: yes it does “handle” them, in a sense that reading the file that contains them will not break the parsing code.
    If you’re asking whether it interprets them then the answer is yes, partially.
    Read “gotchas part of the post”, bullet point starting “Only 4 filters / layer effects are currently supported…”
    The reason why only 4 filters are implemented in this release is that there’s only 5 photoshop effects that are natively implemented in Flash (the 5th one being bevel).
    However, most of the filters, can be “faked” in flash, i.e. implemented via some code tricks. You can for example fake simple outline with glow filter of certain settings, or write a simple implementation for a color fill effects.
    In the next release of this parser , I will read all the filters and record their settings in the specialised filters value objects so such implementations can be made with custom code..

  6. Разработка пожарной декларации в Казани

    Оригинальная идея. Интересно сколько времени он на это потратил

  7. benji

    nice work captain!!!

    tried, tested and works like a charm.

  8. PSD « c# to javascript, actionscript

    […] Slav has an ActionScript implementation. Leave a […]

  9. zproxy

    Waiting for the next version :)

  10. Deevjee

    Nice stuff Slav,
    I’ve one question though.
    In the imagelayer.mxml you have a function called Checklock. When lock is checked the imagelayers are not dragable. but when i uncheck the locks the imagelayers are still not dragable. How can i reorder the imagelayers and make them dragable?

    DJ

  11. Slavomir

    Deevjee:

    you are focusing on the wrong thing here mate :)

    This application is just a quick demo app showcasing some of the uses of the psd parser. I put it together just to be able to preview loaded psds and test some parse-able layer properties.
    You’re supposed to write your own “photoshop” implementation, I did share the code for this PREVIEW app just to make it a bit easier!

  12. Kev

    Nice work,
    I’ve been working on a similar project using the same classes.

    I’ve hit a sticking point. for some reason some of the images I am dealing with appear to have 5 channels.

    Any ideas how to deal with these?

  13. Slav

    Kev:
    Maybe you’re dealing with CMYK images ?
    That’s 4 channels of colour + alpha channel..
    I would try tweaking the PSDLayerBitmap class to read cmyk formats.

  14. Kev

    Cheers Slav,
    that’s what I figured, it’s where I have been focusing my efforts.

    I think if I can work out how its compressed and uncompress it correctly that will solve a lot.

    I’ve been looking at the same bits of code for so long my brain has just frozen – I was so happy to see someone else online working on similar things

  15. Tycho

    Great work!

    Would it be hard to add text layer support? I need the text from the layer + fonts etc but I cannot find clear code to add it into your lib.

    Thanks!

  16. Alex

    Hi there,

    Firs of all GREAT WORK, i’m gona need something like this in a near future, can you just give me a clue how to parse the texts layers as text instead of bitmap?

    Best Regards
    Alexandre

  17. Saqoosha :: Minecraft Skin Viewer

    […] も読めるようにしてあるので(これをちょっと改造)Photoshop で描けます。便利。例によってアプリ本体(AIR […]

  18. Ghada

    Great work!
    Your project was really helpful.
    I’m trying to parse Text layers.How can I get the font type and size?
    I’ll save the layers properties in an XML file .
    Thanx

  19. johannes

    hi slav,
    your psd parser is really really great work and much appreciated by me. i went through the whole parsing process and have to say that i am impressed by how much effort you put into this. i mean, psd is not actually the simplest file protocol…

    however, i am struggling with one certain problem. if i am parsing a psd file with empty layers the parser will fail parsing the content of any layers after parsing an empty layer for the first time. i suppose the problem lies within the function ‘readChannels’ in ‘PSDLayerBitmap’:

    code fragment that i mean:
    ===========================================
    //if layer is empty width*height == 0
    if ((width*height) == 0) //TODO fix this later
    {
    var compression:int = fileData.readShort();
    return;
    }
    ===========================================

    the image data of any subsequent layers will be read falsely afterwards. do you have any idea how i could fix this? i went through the format specification of psd. but this actually is a pain in the a… maybe you have a concise hint for me how to find a solution to this. any help is appreciated.

    cheers, johannes

  20. Slavomir Durej

    Hi Johannes,

    I think what you have to do is to move reading position of the bytearray of psd file. This means advancing forward /skipping forward by the byte length of the empty layer. You can normaly get this size information from the file itself, this should be in specs. I wrote this 2 years ago so don’t remember all the details now, but let me know how you got on, and if you were able to fix this..

  21. johannes

    hi slav,
    thanks for your comments. with your help i am positive that i have been able to solve my problem. in my opinion, when parsing an empty layer the compression field would have been read only once, as after its reading a subsequent return call followed. so if you had 4 channels, only the compression field of the first channel would have been read. the compression fields of the following three layers would not have been read leading to a wrong read position in fileData.

    To fix this problem, I removed the return and encapsulated the whole thing in an if-else clause:
    ===========================================
    if ((width*height) == 0)
    {
    //empty layer. no image data. adjust read position appropriately.
    var compression:int = fileData.readShort();
    }else{
    var channelData:ByteArray = readColorPlane(i,height,width, channelLength)
    if (channelData.length == 0) return; //TODO fix this later

    if (channelID == -1)
    {
    channels[“a”] = channelData;
    //TODO implement [int(ch * opacity_devider) for ch in channel] ; from pascal
    }
    else if (channelID == 0)
    {
    channels[“r”] = channelData;
    }
    else if (channelID == 1)
    //…
    }
    ===========================================

    please note that with this fix to work you have to add the following if clause before calling renderImage at the end of the readChannels function:
    ===========================================
    if ((width*height) > 0){
    renderImage(isTransparent);
    }
    ===========================================

    maybe you could include this somehow in the code.

    have you thought about sharing the code in an online repository like github or google code? there is so many additional stuff that could be added to the code (like smart objects and so on) by other coders…

  22. Nicolas

    It’s great work!
    Could this PSDparser read text(including font-type, size, color, etc) but not as a layer?

  23. felixlzb

    Can you make it supported text layers yet?

  24. minecraft download free full version

    At this time I am going to do my breakfast, later than having my breakfast coming
    over again to read further news.

    my web blog :: minecraft download free full version

  25. how to get minecraft premium for free

    Whats up very cool site!! Guy .. Beautiful .. Amazing
    .. I’ll bookmark your blog and take the feeds additionally?
    I’m satisfied to search out a lot of useful information right here
    within the submit, we want work out more strategies
    in this regard, thank you for sharing. . . . . .

    Check out my web-site how to get minecraft premium for free

  26. minecraft download free full version

    A person necessarily help to make severely
    articles I’d state. That is the very first time I frequented your web page
    and so far? I amazed with the analysis you made to make this actual put up amazing.
    Great task!

    My page :: minecraft download free full version

  27. mode blogs

    With havin so much written content do you ever run into any problems of plagorism or copyright infringement?

    My blog has a lot of completely unique content I’ve either created myself or outsourced but it seems
    a lot of it is popping it up all over the web without my permission.

    Do you know any solutions to help reduce content
    from being stolen? I’d definitely appreciate it.

  28. Combat Arms EU NX Hack

    It’s truly a great and helpful piece of information.
    I’m glad that you shared this useful information with us.
    Please keep us up to date like this. Thanks for sharing.

  29. minecraft premium gratuit la pressemontréal lundi le 13 novembre

    This means there is no mystery why the gaming corporations
    are obtaining massive amounts of money through them.
    If you are considering mods, you can simply mount them.
    The first thing you will need to do is open your command
    prompt and find out which version of Java is installed on
    your computer.

    Feel free to surf to my web-site: minecraft premium gratuit la pressemontréal lundi le 13 novembre

  30. Elsie

    When players consider this there are not
    many games available the same. There are also some services available online,
    which means almost no setup required – just open an account
    and start calling. One reason for this is that it is pretty retro when contrasted to the majority of other
    choices you could choose from.

    Also visit my web blog; Télécharger Minecraft Premium
    Gratuit (Elsie)

  31. Comment Avoir Un Compte Minecraft Premium Gratuitement

    Everything else is pretty significantly just eye candy.
    The Minecraft Survival Guide will be an information
    product that serves to teach novice and experienced
    players on the details of the game at a bit more rapid
    pace than they are accustomed to. There are mods that function to bring more specific content towards the game, mods that maximize your graphics or the
    speed in the game, mods that give new content that had been taken from another game, mods that delete the current content, mods
    that give some other feel to the activity, mods that allow you to
    definitely connect with the Minecraft Top quality Account Generator world in
    many ways, Minecraft Premium Account Generator much
    more.

    Also visit my blog Comment Avoir Un Compte Minecraft Premium Gratuitement

  32. www.yoururl.com

    I am closing, I am sorry, I also would like to express the opinion.

    Also visit my blog: California Psychics Review – http://www.yoururl.com