Newsletter: Herbal viagra Oxaprozin Xanax medication 37 effects phentermine side Taking phentermine Xanax online pharmacy Phentermine diet plan Discount vicodin Generic viagra reviews Amphetamine Erythrityl Order hydrocodone online Phentermine prescriptions Cidofovir Xanax online pharmacy no prescription Xanax effects Xanax and valium Mercaptopurine Fda approved phentermine Estrone 5 free shipping Mexican pharmacy viagra Cefoperazone Hydrocodone cough Lowest price viagra Phentermine 30 mg Approval cialis Herbal phentermine How to get xanax Adipex Actos phentermine aciphex imitrex Cephalexin Free viagra order online Enebrel Cheapest viagra uk Lowest price phentermine 5 no prescription Apomorphine Buy cod pay phentermine Casanthranol Mixing cocaine and viagra Aspirin Phentermine sales online Xanax Cheapest phentermine Pravastatin Us phentermine Viagra kaufen Viagra success story Phentermine 37 5 Phentermine free shipping Meridia diet Lovastatin Book hydrocodone sport Bromocriptine Reglan Didrex Viagra online order guide Imodium Shipping overnight phentermine Cialis info Narcotic tramadol Ceftibuten 5 90 Buy in online uk viagra Diet loss phentermine pill weight Buy viagra online Order generic cialis Ritodrine Nortriptyline 5 mg free shipping Phentermine no perscription required Diamox Lodine Cinnarizine Bontril Imiquimod Buy online prescription viagra without Effects long phentermine side term Long term effects of phentermine use Comparison levivia viagra Santa claus viagra jokes Alphaprodine Mebendazole Effects of xanax Cleocin Prozac interact xanax Paroxetine Belladonna Phentermine mexican pharmacies online Ethinyl Cialis price compare Enoxacin Klonopin Xanax shipped cod Polythiazide Effexor drug interactions with viagra Avodart Clarinex Generic xanax online Female use viagra Letrozole Buy Lipitor Xanax withdrawel symptoms Tramadol hc Bacitracin Viagra pulmonary hypertension Acetaminophen e hydrocodone Soma Neurontin Drug information picture identification tramadol er bvf Luxury hotel rome xanax description Cialis in uk Phentermine blue diet pills $50.00 phentermine Cephapirin Elavil Counterfeit viagra Nystatin Does viagra work Phentermine tablet Xanax dosage Reserpine 1 loss phentermine pill weight Injecting phentermine Zithromax Mexico viagra Carbenicillin Adipex phentermine weight loss Viagra experience Buy buy domain link online online viagra info viag Viagra online ordering Mexiletine Order phentermine cod online Best phentermine pharmacies compare links Do companies sell phentermine with low dose ingredients Withdrawal from xanax Cheap phentermine no prescription Phentermine free shipping Phentermine online without a prescription Phentermine reviews Order phentermine online without perscription Buy generic viagra online Strattera Discount viagra Stopping xanax Cheapest secure delivery cialis uk Lowest phentermine prices Buy online viagra where Differin Cialis for woman Phenergan Selegiline Bar gold xanax Phentermine works Vicodin and alcohol Xanax xr Cheapest viagra price Tramadol hcl tab Cheap phentermine perscription Stavudine Picture viagra pill Cialis uk Buy Soma Chlorpheniramine Purchase soma online Viagra cialis levitra comparison Ativan re valium vs vs xanax Accolate Phentermine adipex diet pill prescription 100 mg viagra Phentermine diet pill Dutasteride Nadolol Injecting xanax Penicillin Discounted phentermine with no prescription Cocaine Uk cheapest viagra Diazepam Buy viagra online get prescription Niacin Cardizem Xenical hgh phentermine quit smoking Cozaar Carvedilol 30mg phentermine Phensuximide Viagra substitute Levaquin Home made viagra Buy phentermine at amide pharmaceutical Xanax online without prescription Risperdal Provigil Cyclobenzaprine Phentermine hcl Phentermine guaranteed overnight shipping Xanax high 37 effects phentermine side Dyphylline Actos Viagra side effects 180 tablet tramadol Phentermine with hoodia Vitamin b12 1000 mcg phentermine and panic attacks Phentermine very cheap Drug interaction sibutramine and phentermine Cheap phentermine free consult Dienestrol Buy cheap online viagra Phentermine prescriptions online Cialis western open Levitra Buy generic online phentermine Mazindol Percocet Buy online pharmacy viagra Buy consultation free hydrocodone online tramadol Phentermine 30 Phentermine and fast shipping Pfizer viagra sperm Hydrocodone overdose Ingredient phentermine Physical symptoms of high blood pressure and xanax Where to buy phentermine Chlortetracycline Buy prescription tramadol without Methotrimeprazine Is viagra safe for woman Hydrochlorothiazide No phentermine prescription Phentermine 37.5 mg sale Viagra use in women Amaryl Ditropan Crestor Sumatriptan Phentermine alternatives Oxaprozin Risperdal Generic soma Ursodiol Dicloxacillin Klonopin versus xanax Cod phentermine Isosorbide Cheap perscription phentermine Cialis new viagra Cheap tramadol prescriptions online How fast will phentermine work Isoflurophate Cheap viagra order online Ceftibuten Symptom tramadol withdrawal Phentermine Simethicone Tramadol online Viagra discussion Generic ambien Losec Free sample viagra Vicodin Cialis compared to viagra Hexoprenaline Nizoral Viagra investigator Viagra cream Buy phentermine no prescription Viagra online shop Phenyltoloxamine Deferoxamine Buy online prescription viagra without Asparaginase Phentermine hcl side effects Hexocyclium Buy no online prescription xanax Phentermine uk Xanax libido Viagra herbal Marijuana Phentermine cash on delivery accepted Oxycontin xanax bars perclesept and lortab wha Compare ionamin phentermine Alavert Cialis sales uk Vicodin without prescription Generic viagra in canada Xanax information Carbamazepine Adderall skin allegra skin xanax skin Bricanyl Buying phentermine James thompson viagra lawsuit Viagra retail discount Apomorphine Grapefruit xanax Perscription cialis Keflex Fatal dose of xanax Buy Levitra Isoproterenol Buy phentermine epharmacist Information about viagra Uk viagra supplier 5 online Free prescription sample viagra Viagra overnight shipping Sulindac Cisapride Phentermine 30mg cap Ansaid Tapering off xanax Glucophage 5mg Glyburide Tramadol hcl acetaminotran Compare levivia and viagra Discount online viagra Cogentin Phentermine and blood in stool Tramadol hydrochloride Why phentermine Online tramadol prescriptions What is viagra Cialis experience Loxapine Tramadol heath solutions network Cheap phentermine cod 180 phentermine Anisindione Cialis co drug eli impotence lilly Rifampin Difference between cialis and viagra Disulfiram Information loss phentermine weight Etanercept Brand drug generic name viagra Diprolene Dilantin Xanax no rx Hydrocodone vicodin Fioricet order Side effects from prozac and xanax Trandolapril Fioricet online Adipex diet phentermine pill How does xanax work Reviparin Vicodin detox Fioricet order Black market phentermine Danazol Buy Alprazolam Viagra patent Viagra overnight shipping Avapro Chlorpromazine Buying viagra on line Aurothioglucose Dipyridamole Phentermine shortage Buy Adderall Tramadol next day Mylan xanax Generic cialis online Carbimazole Black market phentermine Clomiphene Quinacrine Phentermine pharmacy cod Argento soma Cheap xanax Viagra maker Xanax pictures Methocarbamol Female herbal viagra Bontril phentermine adipex Phentermine drug Xanax sexual side effects Viagra use in women Buy phentermine online payment method cod accepted Arimidex Nuvaring Canada cialis generic Phentermine 30 mg Diphenhydramine Ouabain Kanamycin Chloroquine Xanax for dogs Order soma online Orlistat Xanax prescriptions Hydrocodone No prescription needed phentermine Protamine Discount phentermine free shipping Phentermine hydrochloride ship to missouri Cheap phentermine overnight Kanamycin Discount phentermine price Clopidogrel Nicorette Carisoprodol Viagra treatment migraine headache Plendil Colon cleanse ambien Budesonide Dilaudid Iv sample viagra Buy Famvir Nolvadex Phentermine cod Valium vicodin Phentermine 37 5mg and mastercard Where can i buy phentermine Cheap viagra order online On line viagra Phentermine about withdrawl Buy cod pay phentermine Haloperidol Can woman take cialis Phenoxybenzamine Ambien side effects Viagra class action Ways to inject xanax pills Online viagra sale Phentermine cod delivery Tyropanoate Demeclocycline Wholesale pfizer viagra Viagra online sales Buy discount phentermine Buy viagra pill Phentermine discover card Diet pill addiction phentermine Mucomyst Bosch power tools zio lowest viagra Ways to inject xanax pills Buy Xenical Phentermine cash on delivery accepted Nafcillin Best phentermine pharmacies compare links Triamcinolone Online pharmacy phentermine cod Cheap tramadol Canada viagra Phentermine 37 5mg Adipex phentermine vs Estrace Zyban How to get xanax Impotence treatment viagra Esomeprazole Generic xanax xr Diatrizoate Purchase viagra online Ibuprofen Phentermine and birth defects Lowest drug price for phentermine Viagra online store Purchase cialis online Diclofenac 5mg phentermine Dangers of phentermine Xanax no prescription Physical symptoms of high blood pressure and xanax Compare pharmacies for phentermine Xanax american express Vicodin without prescription Diethylstilbestrol Taking xanax while pregnant High cortisol level phentermine Does phentermine interact with hydrocodone Lynestrenol Alternatives to phentermine Lowest cost phentermine Cheap viagra online prescription Overnight xanax or alprazolam delivery Buy viagra online cheap Phentermine cash on delivery Iv sample viagra Lyrica Online tramadol prescriptions Xanax during pregnancy Doxycycline Methdilazine Phenytoin Buspar xanax Avelox Hyzaar Cytotec Buy cod online phentermine Xenical hgh phentermine quit smoking Phentermine free delivery Long term side effects of xanax Bad side effects of viagra Xanax tablet Elavil Ambien prescription Tolbutamide Compare levivia and viagra Buy hydrocodone overnight Phentermine pharmacies Phentermine dangerous Catapres Heroin Phentermine lowest price 37.5 online On line doctor phentermine Tramadol without prescription Ticarcillin Cialis in the uk Compare ionamin phentermine Tamoxifen Hexachlorophene Crestor Cefadroxil Discount pharmacy phentermine purchase Dimethothiazine Buy Paxil Cialis discount online Droperidol Phentermine money order Levivia viagra Viagra best buy Viagra results Order phentermine online Online tramadol Cyclamate Low price phentermine Viagra cialis levivia comparison dosages Fastin Canadian viagra Cheap tramadol cod Cod online tramadol Meridia better than phentermine Buy phentermine yellow Abilify Viagra lawsuit Uk viagra suppliers Buy Meridia Order phentermine c o d Cheap phentermine overnight delivery Buying phentermine without prescription Enebrel Phentermine without perscription Pyrimethamine Dopamine Diet diet dieting phentermine pill Tramadol no prescription Prempro Thiphenamil Senna Cialis comparison levitra Xanax versus klonopin for chronic anxiety Buy domain onlinebigsitecitycom phentermine Vicodin side effects Ecotrin Methazolamide Colesevelam Celecoxib Labetalol Online viagra prescriptions Cephalothin Trimetrexate Felodipine Discount drug viagra Mecamylamine Phentermine withdrawal Cialis tadalafil Cefoxitin Buy phentermine on line Lanoxin Phentermine hydrochloride Atorvastatin Mail order viagra online Secobarbital Isradipine Drug laws ohio diet phentermine Viagra information Midodrine Permax Hydrocodone withdrawal Prednisolone Alteplase Fluticasone Amitriptyline Cialis forums Lovenox Effects of xanax Xanax online cheap Epoprostenol Ibuprofen

Dependency injection in flex

Finally I played with inversion of control in flex. It was only one thing that I missed in big actionscript application. Here is sample dependencytest.zip

Start conditions

To implement dependency injection need a way to access to each class in application in order to define if it marked with metadata or not. Metaprogramming way can simplify, automate usage of util. But here is one problem. How to get access to all classes in application. Here could be 3 ways:
* Write list of classes in code manually. The most easy and lightweight solution. But have small inconvenience so need add each new class to list.
* Write configuration files and put there names of classes that need to instantiate. Most complex for use but not hard to implement way. It also gives few excess abilities.
* Add ability to load current swf into itself and parse it in order to find included classes. Most complex to implement and application have some delay in start. In other side it is easy to use that solution.
I tried 3rd one because it easy to use by developer and most complex work is already done. So loading and parsing swf are possible and available in open source libraries. See previous post. To marking class as bean metadata was used. Using metadata gives such easy flexibility.
If you found 3rd way isn’t good for your application you still can use 1st way with declaring classes manually.

Make it easy

I decided not to write complex system for dependency injection. So the main needed requirement is having initialized beans with injected dependencies. As for me that is enough for most cases. Here is few simple steps to start:
1. To mark class as singleton bean just need to put “Dependency” metadata over the class definition.

[Dependency]
public class AccountModel

Don’t forget to include this custom metadata into flex configuration file: flex-config.xml
2. To have a value of bean passed to your class instance need to declare public property or accessor with the same name. For example you need inject AccountModel then define accountModel accessor:

private var _accountModel:AccountModel;
public function set accountModel(value:AccountModel):void {
_accountModel = value;
}

3. If you want to create instance and setup it with all available beans dependencies then use:

var command:BootCommand = dependencyUtil.createInScope(BootCommand) as BootCommand;

Power of simplicity

You may notice that here is no way for defining two beans of same type or set a custom name to bean. As for me it’s not a big problem and most of goals still can be achieved via following name convention. Where this dependency injection is useful:
1. Defining a single instance per application of some class. It is realy a pain to access application models without IoC. You have to make all your models classes as singleton or put them into static/singleton facade. And manually retrieve model instances at the beginning of code or class. Dependency injection allow easy to mark class to export as singleton and inject it instance to other singletons at startup.
2. Create new controllers (in case you are using Cairngorm or similar architecture) with injecting dependencies. You can skip declaring models or delegates values in your controllers. Usually it is done via ServiceLocator or ModelLocator. You only need to override command initialization way so using dependencyUtil.createInScope instead of new Command().

Conclusion

My sample code adds to project 60KB when used. But if you get rid out of complex swf parsing then size of util could be 5KB! So it can be small and still power. Size of application still matter for web applications. Util metadata in actionscript instead of configuration files. That gives simplicity for user but maybe restrict in some future features.

Get list of classes in flex application

This isn’t common goal for developers. And furthermore problem solving isn’t easy. Actionscript code doesn’t give access to available classes at runtime. So only trick I can image is parsing swf file by itself and get class names. Crazy implementation? Yes, it is. :-) But no coding here because flash decompilers written in actionscript already exist.

Swfassist:
Nice library that gives ability to write and read tags in swf files. Developers are from Japan as I understand so it’s hard to determine full feature list. But I found no way to determine loaded class info there. It repo.

FlashDecompiler:
Cool air application that can load and decompile swf files.

For accomplishing my goal I took FlashDecompiler source and used only needed classes. Unfortunally code had a lot of dependency so I had to cut/change project code. Finally I got 60KB code for retrieving class info. And it is not only one inconvenience. Application load and parse swf at start time so it take few excess second to start. But I still think that it is acceptable. Here is cutted code.

You might ask me for why it is needed? He-he. That could open door for few nice features. You can build dependency injection engine by marking classes with specific metadata. That’s the main goal. Currently Flash Player gives only info about class by it name. But need to know which classes marked with specific metadata. That is what I’m going to implement.

Update 1:

I found more short way to get bytes of current runned swf. It is available via next code in Application class

systemManager.loaderInfo.bytes

So now no needs to load current swf file again. Sample code updated.

DateChooser cook page: emphasizing some dates

DateChooser component in flex is nice but changing its behavior isn’t easy. To make easy step such as coloring (highlighting) background in pointed dates you need make real hack. Extending DateChooser stopped on component encapsulation. It prevent access because a lot of fields marked as private.

DateChooser with emphasized dates

There are many people asked for custom date highlighting in mailing list but only one existed solution exists in old post. In our current project we have to adjust it for Flex 3 Beta 3. So here is RangeChooser with sources.

Give user a choice to select font

Subject with loading font isn’t new but some its part weren’t still described. Or I missed them and had to walk through debugging nightmare.

So target application is text/image editors on flash that gives user option to be unique and change font style of his label. And the problem is the font as other graphic content has some weight. Including fonts to application affect on user traffic and experience, because user has to wait longer. And here usually comes idea don’t load all fonts with application and load them only when user require it.

Many projects don’t include fonts into application and load needed on demand. You can found great example at Picnik Editor . All displayed fonts weren’t loaded on at the beginning. Them are loading only when user select them. In that way application size reduced a lot. For example Arial Black font has complete size – 45KB. It is including basic latin lowercase, uppercase, numeric and punctuation characters. Also in 4 styles: regular, bold, italic, bold italic. But Arial Black is smallest font. Other ones which are more artistic can be more then 150KB. So solution is to preload fonts on demand.

Loading

Loading font into flash application at runtime is simple task. You can find ready to use solutions there:
Loading fonts example
Loading fonts util
To use font in application need to load it and register via Font.registerFont(); Then it will be ready to use in your text:
textfield.embedFonts = true;
textfield.setTextFormat(new TextFormat(“Font name”));
Second utility above is hardcore implementation. It gives ability to load fonts packed into swf versions 7, 8, 9.
If successfully tried some utility and got textfield with correct font that’s great. But it isn’t final.

Font preparation

Loading font is half of goal. Flash Player can’t load font as ttf. Flash will recognize font only if it packed in swf. You might need to create couple of fonts ready to load. For example you let user to choose 20 fonts. Then it’s need to get 20 swf files with these fonts. Or 80! if you are going to load each style separately (regular, bold, italic or bolditalic). That’s might be nightmare and chores. Especially if you don’t know exactly which symbols need to include.

Here swfmill might be useful. It’s rock util for swf generation. So generation of single swf file with one font style looks like:

<?xml version="1.0" encoding="iso-8859-1" ?>
<movie width="1" height="1" framerate="12">
<background color="#ffffff"/>
<frame>
<library>
<font import="font/arialbold.ttf" glyphs=" abcdefghijklmn
opqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345
6789!#$%^*()-=_+,.?/ "&<>'"/>
</library>
</frame>
</movie>

So you can facilitate goal and work with xml instead of fla files. Instead of 20 fla files you might have 20 xml files which are easy to modify (replace content). But here is few problems. This implementation requires that you have ttf file for each font style. For example for Arial: arialregular.ttf, arialbold.ttf, arialitalic.ttf, arialbolditalic.ttf. Some fonts might be packed at single file for example you may find arial.ttf with all styles. But swfmill can read only first font inside file. Another problem of swfmill that it is create swf file up to 8 version.

Finally jsfl can save you from troubles. Spending few hours to reading API documentation you can write script for swf generation in jsfl. Or certainly using my one. Script create blank flash document, put textfield on stage set it font and embedded symbols. Then compiles to many swf files with different predefined fonts. As result you got single file with ability easy to change embedded symbols type. Easy to add new font. Sure it’s need to have fonts already installed at you OS. I like automation.

Font thumbnails

Next feature is styled list of fonts. It’s better if user choose font by visual representation instead of plain text name.

Styled list

As you might have noticed at picnik fonts labels are styled, means that font already applied to it. It can be done by creating separate swf with incuding only symbols used in font label. For example for label “Palatino Linotype”, it’s need to include regular style of chars “Paltino Lype”. It also can be generated with jsfl.

Problems

It is impossible to develop in flash without stumble over problems. One of them makes a real pain. If your application already has embedded font you can’t register loaded symbols. For example you have a static Arial text “Welcome”. You will fail to use other Arial symbols in application via loading font. So you must to embed all Arial font to fla or don’t use or either. Font symbols becomes embedded in next cases:
• when you put static text on stage. If you will put static text
• when you put dynamic or input text with including chars

You can easy check if you swf has embedded font. Just decompile it with SWFDecompiler. It hasn’t support of version 9 but it still display used assets in swf. And there you can find what fonts are embedded and glyphs count. But looking for  embedded font in big fla isn’t simple. Here some jsfl script might be usefull again.

Hurry up to buy gifts!

Singleton template in flex builder

Наткнулся на пост в рунете о плагине Eclipse Monkey. Если коротко, то это плагин который позволяет описывать на javascript темплейты генерации кода для Eclipse. Судя по примерам через javascript можно даже оперировать с java классами в еклипсе. Затронуло. Для actionscript разработчиков, чьи будни проистекают в Flex Builder, monkey может стать бензопилой по коду. Которая избавляет от рутинной работы лобзиком. Java программистам так может не показаться. Так как у них достаточно средств для рефакторинга встроенных в JDT.

Не сложилось, почему-то у Adobe добавить возможность генерации кода по темплейтам. Теперь есть шанс опробовать monkey. Думаю, опыт работы с плагином может пригодиться даже после того как в Flex Builder появяться темплейты. Так как выполняемые задачи могут быть связаня не только с генерацией кода, а и с реплейсом многих участков, а не только выделенного.

Итак, каждый доселе каждый написавший об этом плагине написал темплейт к нему. Чем займусь и я ради разминки мозгов. Вот и наваял темплейт который генерирует заготовку singleton паттерна. Темплейт сдеся. Чтоб использовать его, нужно создать новый actionscript 3.0 класс и вызвать мой темплейт.

О том, как вызывать темплейты читайте на домашней странице плагина или там где я подсмотрел новость.

Пара типсов для написания собственного темплейта:
1. Чтобы узнать имя редактируемого класса:
editors.activeEditor.title
2. Чтобы заменить текст в редакторе используеться код:
editor.applyEdit(insertPos, deleteCount, text);
3. О том, как слать сообщения в консоль читайте здесь

Ссылки:

BitmapUtil for changing image contrast, brightness in actionscript.

[lang_ru]
Речь пойдёт о маленькой библиотечке для работы с BitmapData. С помощью этого кода можно быстро написать редактор изображений. Думаю вариантов применения множество. Можно прикрутить редактор к фото-галерее на флеше. Разуметься если в проекте контент включает картинки. Демка и все исходники прилагаются.

Описание и возможности
С помощью BitmapUtil вы сможете:

  • изменять контрастность;
  • изменять яркость;
  • изменять насыщенность;
  • делать эффект негатива;
  • увеличивать/уменьшать изображение;
  • растягивать по вертикали/горизонтали;
  • вырезать прямоугольный участок изображения;
  • вращать изображение вокруг центра;
  • добавлять рамку к изображению – простые полоски определённого цвета и толщины
  • добавлять другие изображения – добавляемые части могут быть как BitmapData или графические элементы IBitmapDrawable. Это функция очень параметризируемая. Для добавляемой части можно задавать угол вращения, прозрачность, размер.

Чего не хватает – это простого рисования кисточкой. У меня в проекте не было необходимости. Но скорей всего это бы делалось с помощью addUIToBitmap.

Моя демка на flex’e
BitmapUtil demo in flex
Все исходники здесь

Внутри
Для работы, прежде всего, нужно загрузить картинку. Как это сделать сами знаете. Возможно, случиться трудность с загрузкой картинки с сервера, отличного от того, с которого запущена флешка. Картинка загрузится нормально, и отобразиться, но вот преобразовывать её BitmapData с ней не получиться. По выданной ошибке (SecurityError), вы можете понять, что нужно загрузить также policy file. Например, так:

loader.load(new URLRequest(url), new LoaderContext(true));

Объект типа BitmapData получаем из loader.content, если картинка была загружена с помощью класса flash.display.Loader.
Все операции с пикселями изображения проходят на клиентской стороне. И в результате получается отредактированный растр, который останется только сохранить в файл. Не требуется отсылать серверу команды, рода «изменить контрастность +20» и потом загружать обработанное изображение. Flash Player и сам прекрасно справляется с преобразованиями растра.

Пример использования:

var oldBitmap:Bitmap;
var bitmapUtil:BitmapUtil = new BitmapUtil();
var newBitmap = bitmapUtil.contrast(oldBitmap, 50);

Так вы получите изображение с повышенной контрастностью.
Документировать все методы класса я не счёл необходимым. Думаю, по их названиям понятно, что они выполняют. Возможные значения аргументов я пометил.

Ещё пару заметок при работе с BitmapData:
1. Нужно очищать BitmapData, если она вам боле не нужна: BitmapData.dispose().
2. Даже если вы вызвали dispose(), то Garbage Collector не сразу очистит память. Если вы проводите много операций с растром, то используемая память будет безмерно разрастаться. И по завершению лучше форсировать gc. Как это предлагает Грант:

try {
new LocalConnection().connect('foo');
new LocalConnection().connect('foo');
} catch (e:*) {}

У меня самого тоже получалось вызвать gc путём изменения размера flash окна.
3. Будьте начеку. Максимальный размер BitmapData 2880 x 2880 px.

Производительность
Почти в каждом методе bitmapUtil создается и уничтожается объект bitmapData (собственно в нём храниться массив с пикселями). В коде есть ещё места для оптимизации. Но с форсированием gc, приложение в работе не кажется медленным. И для картинки 800 на 600 трансформации происходят быстро.

[/lang_ru]
[lang_en]

It is small library for work with BitmapData. You can easy create image editor with this code. There are many variants of library usage. Demo and all sources are included.

Description
Library can be used in flex of actionscript 3.0 project. Actually there is only one class in library. It contains public methods that do ations with image.
Next is possible with BitmapUtil:

  • To change the contrast;
  • To change the brightness;
  • To change the saturation;
  • To do the effect of negative;
  • To enlarge or to miniaturize of pictures;
  • To elongate by horizontal or vertical;
  • To crop the rectangular part from picture;
  • To rotate the picture from the centre;
  • To add the border to picture – is simple stripe with defined color and thickness;
  • To add some other pictures – the adding parts can be BitmapData or graphical elements IBitmapDrawable. This function is much parameterized. You can assign the rotation, transparency and scaling for added part.

There are no lines or brush drawing in the library. I didn’t need that in my project. I think it can be implemented too with method addUIToBitmap.

Demo in flex
BitmapUtil demo in flex
All sources here

Inside
Off course its need to load image first. And I’m sure you know how to do that. The one problem can happened with image loading. If it was loaded from server another from swf was running. The picture shown well but it will be impossible to edit its BitmapData. The SecurityError can be thrown. Then you need load policy file like:

loader.load(new URLRequest(url), new LoaderContext(true));

If image was loaded with flash.display.Loader, then the object with type of BitmapData can be obtained from loader.content.
All operation on image pixels processed in client-side. As result we get edited raster, which is need to save. It’s no need to send command like “change contrast +20” and load edited image from server. Flash Player can do that itself.

Usage sample:

var oldBitmap:Bitmap;
var bitmapUtil:BitmapUtil = new BitmapUtil();
var newBitmap = bitmapUtil.contrast(oldBitmap, 50);

So you get and more contrasted image.
I didn’t add docs to all methods in class. I think it will be enough name of method to define its functionality. I defined possible range of methods arguments.

Few notices about BitmapData usage:
1. Its need to clean BitmapData object, if it isn’t needed: BitmapData.dispose().
2. If you call dispose(), that object maybe not erased from memory immediately. If you work with raster, then Flash Player memory usage may growth a lot. It works good if we force actionscript 3.0 garbage collector like Grant said:

try {
new LocalConnection().connect('foo');
new LocalConnection().connect('foo');
} catch (e:*) {}

I noticed myself that garbage maybe called while flash window resized.
3. Take in mind that maximum size of BitmapData is 2880 x 2880 px.

Performance
Each BitmapUtil method creates and destroys object with type BitmapData (it contains array with pixels). Some places for optimization are in the code. But application doesn’t looks slow with forced Garbage Collector. And all transformation goes quickly for image 800 x 600.

[/lang_en]

Welcome

[lang_en]

Salute!!!
Finally it happened. I have my own site. It was a very, very long way. And now I will migrate in virtual world.
I love flash technology and things that done in flash. With flash you can do both programming and design pearls. Every week I see flash projects that raise my mood up. I like flash games, I like flash sites, and I like flash movies.

So this blog will be mostly about flash platform. I’m going to put my work notice here. And cover world’s flash news.

I hope I will be a good writer. Let me start.

[/lang_en]

[lang_ru]

Салют!!!
Наконец-то это свершилось. У меня появился сайт. Ну, уж очень долго пришлось к этому идти. Ну да ладно, спасибо друзьям, помогли, а то ещё б пол года разбирался с php и хостингом. Есть Интернет, есть сайт и есть я, надеюсь из этого, что-то получиться. Начинаем переселяться в виртуальный мир. Теперь и мне будет, где показать, а кому-то – где посмотреть.

Flashcrafter?
Нечто напоминающее мне startcraft, warcraft.
Чем флеш не ремесло? Вот сижу целыми днями в цехе и вытачиваю кнопочки, панельки. Леплю видео плееры. Думаю удачное сочитание flash + craft. Мне нравиться. Жаль только что домен flashcraft.com был забронирован.

Что здесь будет?
Так как я флеш программист, то писать собираюсь в большинстве о флеше. О своих наработках и о происходящем вокруг. То есть блог будет технический. Хотелось бы открыть раздел аля labs или workshop. Но это слишком время пожирательные вещи для одного человека.

Что хочу?
Кроме квартиры в центре Киева… хочу сделать свой отпечаток в Интернете.

Буду переучивать себя в писателя. Да прибудет со мной энтузиазм и муза.
[/lang_ru]