as3corelib Tutorial:How to Use JPEGEncoder and PNGEncoder Class in Flex

orbz-nature-256x256The most popular image codecs on the internet are JPEG, PNG and GIF. However, GIF(http://code.google.com/p/as3gif/) is another stuff I will show you in another article. Here shows a BMPEncoder as well for a comparison to JPEGEncoder and PNGEncoder, and maybe you will find it’s useful in case.

Search-256x256 Demo | DownloadDownload Full Project

  1. This demo shows the usage of the classes JPEGEncoder and PNGEncoder provided by as3corelib, and the usage of BMPEncoder provided by Trevor McCauley(http://www.senocular.com).
  2. Enter the words you want to write on the background image.
  3. Click "save to JPG image" to save the canvas as a JPG file;Click "save to PNG image" to save the canvas as a PNG file;Click "save to BMP image" to save the canvas as a BMP file.
  4. The status of panel will show you the exact "time costs" to encode the image in miliiseconds.
  5. At last, you will find that the size of PNG file is smallest, next is JPG file, the BMP file is the lagest one. However, the encoding of BMP is fatest, next is PNG, the slowest is JPG.
  6. Using the check box at the bottom to compare the performances of the encoding methods provided by as3corelib "com.adobe.images" and adobe "mx.graphics.codec". If it is unchecked, the encoding methods are "com.adobe.images.JPGEncoder.encode" and "com.adobe.images.PNGEncoder.encode", else they are "mx.graphics.codec.JPEGEncoder.encode" and "mx.graphics.codec.PNGENcoder.encode".

Thanks the authors of as3corelib, thanks Trevor McCauley, who provides us the BMPEncoder, as well.

class JPGEncoder

Class that converts BitmapData into a valid JPEG

Methods

JPGEncoder()

  1. public function JPGEncoder(quality:Number = 50)
  2. Constructor for JPEGEncoder class

Parameters

  1. quality:Number (default = 50)The quality level between 1 and 100 that detrmines the level of
  2. compression used in the generated JPEG

encode()

  1. public function encode(image:BitmapData):ByteArray
  2. Created a JPEG image from the specified BitmapData

Parameters

  1. image:BitmapDataThe BitmapData that will be converted into the JPEG format.

Returns

  1. ByteArraya ByteArray representing the JPEG encoded image data.

class PNGEncoder

Class that converts BitmapData into a valid PNG.

Methods

encode()

  1. public static function encode(img:BitmapData):ByteArray
  2. Created a PNG image from the specified BitmapData

Parameters

  1. img:BitmapDataThe BitmapData that will be converted into the PNG format.

Returns

  1. ByteArraya ByteArray representing the PNG encoded image data.

Demo Screenshot

ImageEncoderDemo

The following is full source code:

main.css

Download: main.css
  1. /* CSS file */
  2. Application
  3. {
  4.     fontSize:12;
  5. }

FontLoader.as

Download: FontLoader.as
  1. package
  2. {
  3.     import flash.events.Event;
  4.     import flash.events.EventDispatcher;
  5.     import flash.events.IEventDispatcher;
  6.     import flash.text.Font;
  7.  
  8.     import mx.core.Application;
  9.     import mx.styles.StyleManager;
  10.  
  11.     public class FontLoader extends EventDispatcher
  12.     {       
  13.         private static var loaded:Boolean = loadEmbedFonts();
  14.  
  15.         private static function loadEmbedFonts():Boolean
  16.         {
  17.             var deviceFonts:Array = Font.enumerateFonts(true);
  18.             Application.application.fonts = deviceFonts;
  19.             return true;
  20.         }
  21.     }
  22. }

ImageEncoderDemo.as

  1. package
  2. {
  3.     import com.adobe.images.JPGEncoder;
  4.     import com.adobe.images.PNGEncoder;
  5.     import com.senocular.images.BMPEncoder;
  6.  
  7.     import flash.display.BitmapData;
  8.     import flash.events.KeyboardEvent;
  9.     import flash.net.FileReference;
  10.     import flash.ui.Keyboard;
  11.     import flash.utils.ByteArray;
  12.  
  13.     import mx.containers.Canvas;
  14.     import mx.controls.CheckBox;
  15.     import mx.controls.TextArea;
  16.     import mx.core.Application;
  17.     import mx.events.ColorPickerEvent;
  18.     import mx.events.ListEvent;
  19.     import mx.graphics.codec.JPEGEncoder;
  20.  
  21.     public class ImageEncoderDemo extends Application
  22.     {
  23.         public function ImageEncoderDemo()
  24.         {
  25.             super();
  26.         }
  27.  
  28.         public var text:TextArea;
  29.         public var canvas:Canvas;
  30.         public var isCorelib:CheckBox;
  31.  
  32.         [Bindable]
  33.         public var fonts:Array;
  34.  
  35.         [Bindable]
  36.         protected var costTime:Number = 0;
  37.  
  38.         protected function fontsChangeHandler(event:ListEvent):void
  39.         {
  40.             text.setStyle("fontFamily",event.currentTarget.selectedItem.fontName);
  41.         }
  42.  
  43.         protected function textColorChangeHandler(event:ColorPickerEvent):void
  44.         {
  45.             text.setStyle("color",event.color);
  46.         }
  47.  
  48.         protected function canvasColorChangeHandler(event:ColorPickerEvent):void
  49.         {
  50.             canvas.setStyle("backgroundColor",event.color);
  51.         }
  52.  
  53.         protected function application_KeyDownHandler(event:KeyboardEvent):void
  54.         {
  55.             if(event.keyCode == Keyboard.ESCAPE)
  56.             {
  57.                 application.setFocus();
  58.             }
  59.         }
  60.  
  61.         protected function save(type:String):void
  62.         {
  63.             var bitmapData:BitmapData = new BitmapData(canvas.width,canvas.height);
  64.             bitmapData.draw(canvas);
  65.  
  66.             var encoder:Object = new Object();
  67.             var defaultName:String;
  68.  
  69.             switch(type)
  70.             {
  71.                 case "JPG":
  72.                 {
  73.                     var je:*;
  74.                     if(!isCorelib.selected)
  75.                     {
  76.                         je = new JPGEncoder(100);                           
  77.                     }
  78.                     else
  79.                     {
  80.                         je = new JPEGEncoder(100);
  81.                     }
  82.  
  83.                     encoder.encode = je.encode;
  84.                     defaultName = "myImage.jpg";
  85.                     break;
  86.                 }
  87.                 case "PNG":
  88.                 {
  89.                     if(!isCorelib.selected)
  90.                     {
  91.                         encoder.encode = PNGEncoder.encode;
  92.                     }
  93.                     else
  94.                     {
  95.                         var pe:mx.graphics.codec.PNGEncoder = new mx.graphics.codec.PNGEncoder();
  96.                         encoder.encode = pe.encode;
  97.                     }
  98.                     defaultName = "myImage.png";
  99.                     break;
  100.                 }
  101.  
  102.                 case "BMP":
  103.                 {
  104.                     encoder.encode = BMPEncoder.encode;
  105.                     defaultName = "myImage.bmp";
  106.                     break;
  107.                 }
  108.             }
  109.  
  110.             var time:Date = new Date();           
  111.             costTime = time.getTime();
  112.  
  113.             var imageBytes:ByteArray = encoder.encode(bitmapData);
  114.  
  115.             time = new Date();
  116.             costTime = time.getTime() - costTime;
  117.  
  118.             var fr:FileReference = new FileReference();
  119.             fr.save(imageBytes,defaultName);
  120.         }
  121.     }
  122.  
  123. }

ImageEncoderDemoView.mxml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ImageEncoderDemo
  3.     xmlns="*" 
  4.     xmlns:mx="http://www.adobe.com/2006/mxml"
  5.     layout="vertical" xmlns:local="*"
  6.     keyDown="application_KeyDownHandler(event)" >
  7.     <mx:Style source="assets/css/main.css"/>
  8.     <local:FontLoader/>
  9.     <mx:ApplicationControlBar 
  10.         width="100%">
  11.         <mx:ComboBox 
  12.             labelField="fontName"
  13.             dataProvider="{fonts}"
  14.             change="fontsChangeHandler(event);"/>
  15.         <mx:Label text="text color"/>
  16.         <mx:ColorPicker
  17.             change="textColorChangeHandler(event);"/>
  18.         <mx:Label text="canvas color"/>
  19.         <mx:ColorPicker
  20.             change="canvasColorChangeHandler(event);"/>
  21.     </mx:ApplicationControlBar>
  22.  
  23.     <mx:Panel 
  24.         title="Image Encoder Demo"
  25.         width="100%"
  26.         height="100%"
  27.         status="time costs: {costTime} milliseconds">
  28.         <mx:Canvas id="canvas" 
  29.             width="100%" 
  30.             height="100%"
  31.             backgroundColor="#000000">
  32.             <mx:Image 
  33.                 source="assets/image/web20_Source.png"
  34.                 width="100%" 
  35.                 height="100%"/>
  36.  
  37.             <mx:TextArea id="text" 
  38.                 width="100%"
  39.                 height="100%"
  40.                 backgroundAlpha="0"
  41.                 focusIn="event.currentTarget.setStyle('backgroundAlpha',0.5)" 
  42.                 focusOut="event.currentTarget.setStyle('backgroundAlpha',0)"
  43.                 color="#ffffff"
  44.                 >
  45.                 <mx:htmlText>
  46.                     <![CDATA[1.This demo shows the usage of the classes JPEGEncoder and PNGEncoder
  47. 2.Enter the words you want to write on the background image.
  48. 3.Click "save to JPG image" to save the canvas as a JPG file;Click "save to PNG image" to save the canvas as a PNG file;Click "save to BMP image" to save the canvas as a BMP file
  49. 4.The status of panel will show you the exact "time costs" to encode the image in miliiseconds.
  50. 5.At last, you will find that the size of PNG file is smallest, next is JPG file, the BMP file is the lagest one. However, the encoding of BMP is fatest, next is PNG, the slowest is JPG.
  51. 6.Using the check box at the bottom to compare the performances of the encoding methods provided by as3corelib "com.adobe.images" and adobe "mx.graphics.codec". If it is unchecked, the encoding methods are "com.adobe.images.JPGEncoder.encode" and "com.adobe.images.PNGEncoder.encode", else they are "mx.graphics.codec.JPEGEncoder.encode" and "mx.graphics.codec.PNGENcoder.encode".]]>
  52.                 </mx:htmlText>
  53.             </mx:TextArea>
  54.         </mx:Canvas>
  55.  
  56.         <mx:ControlBar>
  57.             <mx:CheckBox id="isCorelib" label="use core lib encoders (unchecked) or adobe encoders (checked)?"/>
  58.             <mx:Button label="save to JPG image" click="save('JPG');"/>
  59.             <mx:Button label="save to PNG image" click="save('PNG');"/>
  60.             <mx:Button label="save to BMP image" click="save('BMP');"/>
  61.         </mx:ControlBar>       
  62.     </mx:Panel>
  63.  
  64. </ImageEncoderDemo>
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed
You can leave a response, or trackback from your own site.

3 Responses to “as3corelib Tutorial:How to Use JPEGEncoder and PNGEncoder Class in Flex”

  1. Marc Pelland says:

    is the FileReference.save something in the Flex library only? i can’t find that function.

  2. Marc Pelland says:

    nevermind.. flash 10 only. got it.. ps great tutorial :)

Leave a Reply