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

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

Parameters

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

encode()

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

Parameters

image:BitmapData — The BitmapData that will be converted into the JPEG format.

Returns

ByteArray — a ByteArray representing the JPEG encoded image data.

class PNGEncoder

Class that converts BitmapData into a valid PNG.

Methods

encode()

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

Parameters

img:BitmapData — The BitmapData that will be converted into the PNG format.

Returns

ByteArray — a ByteArray representing the PNG encoded image data.

Demo Screenshot

ImageEncoderDemo

The following is full source code:

main.css

/* CSS file */
Application
{
	fontSize:12;
}

FontLoader.as

package
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.text.Font;

	import mx.core.Application;
	import mx.styles.StyleManager;

	public class FontLoader extends EventDispatcher
	{
		private static var loaded:Boolean = loadEmbedFonts();

		private static function loadEmbedFonts():Boolean
		{
			var deviceFonts:Array = Font.enumerateFonts(true);
			Application.application.fonts = deviceFonts;
			return true;
		}
	}
}

ImageEncoderDemo.as

package
{
	import com.adobe.images.JPGEncoder;
	import com.adobe.images.PNGEncoder;
	import com.senocular.images.BMPEncoder;

	import flash.display.BitmapData;
	import flash.events.KeyboardEvent;
	import flash.net.FileReference;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;

	import mx.containers.Canvas;
	import mx.controls.CheckBox;
	import mx.controls.TextArea;
	import mx.core.Application;
	import mx.events.ColorPickerEvent;
	import mx.events.ListEvent;
	import mx.graphics.codec.JPEGEncoder;

	public class ImageEncoderDemo extends Application
	{
		public function ImageEncoderDemo()
		{
			super();
		}

		public var text:TextArea;
		public var canvas:Canvas;
		public var isCorelib:CheckBox;

		[Bindable]
		public var fonts:Array;

		[Bindable]
		protected var costTime:Number = 0;

		protected function fontsChangeHandler(event:ListEvent):void
		{
			text.setStyle("fontFamily",event.currentTarget.selectedItem.fontName);
		}

		protected function textColorChangeHandler(event:ColorPickerEvent):void
		{
			text.setStyle("color",event.color);
		}

		protected function canvasColorChangeHandler(event:ColorPickerEvent):void
		{
			canvas.setStyle("backgroundColor",event.color);
		}

		protected function application_KeyDownHandler(event:KeyboardEvent):void
		{
			if(event.keyCode == Keyboard.ESCAPE)
			{
				application.setFocus();
			}
		}

		protected function save(type:String):void
		{
			var bitmapData:BitmapData = new BitmapData(canvas.width,canvas.height);
			bitmapData.draw(canvas);

			var encoder:Object = new Object();
			var defaultName:String;

			switch(type)
			{
				case "JPG":
				{
					var je:*;
					if(!isCorelib.selected)
					{
						je = new JPGEncoder(100);
					}
					else
					{
						je = new JPEGEncoder(100);
					}

					encoder.encode = je.encode;
					defaultName = "myImage.jpg";
					break;
				}
				case "PNG":
				{
					if(!isCorelib.selected)
					{
						encoder.encode = PNGEncoder.encode;
					}
					else
					{
						var pe:mx.graphics.codec.PNGEncoder = new mx.graphics.codec.PNGEncoder();
						encoder.encode = pe.encode;
					}
					defaultName = "myImage.png";
					break;
				}

				case "BMP":
				{
					encoder.encode = BMPEncoder.encode;
					defaultName = "myImage.bmp";
					break;
				}
			}

			var time:Date = new Date();
			costTime = time.getTime();

			var imageBytes:ByteArray = encoder.encode(bitmapData);

			time = new Date();
			costTime = time.getTime() - costTime;

			var fr:FileReference = new FileReference();
			fr.save(imageBytes,defaultName);
		}
	}

}

ImageEncoderDemoView.mxml

<?xml version="1.0" encoding="utf-8"?>
<ImageEncoderDemo
	xmlns="*"
	xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="vertical" xmlns:local="*"
	keyDown="application_KeyDownHandler(event)" >
	<mx:Style source="assets/css/main.css"/>
	<local:FontLoader/>
	<mx:ApplicationControlBar
		width="100%">
		<mx:ComboBox
			labelField="fontName"
			dataProvider="{fonts}"
			change="fontsChangeHandler(event);"/>
		<mx:Label text="text color"/>
		<mx:ColorPicker
			change="textColorChangeHandler(event);"/>
		<mx:Label text="canvas color"/>
		<mx:ColorPicker
			change="canvasColorChangeHandler(event);"/>
	</mx:ApplicationControlBar>

	<mx:Panel
		title="Image Encoder Demo"
		width="100%"
		height="100%"
		status="time costs: {costTime} milliseconds">
		<mx:Canvas id="canvas"
			width="100%"
			height="100%"
			backgroundColor="#000000">
			<mx:Image
				source="assets/image/web20_Source.png"
				width="100%"
				height="100%"/>

			<mx:TextArea id="text"
				width="100%"
				height="100%"
				backgroundAlpha="0"
				focusIn="event.currentTarget.setStyle('backgroundAlpha',0.5)"
				focusOut="event.currentTarget.setStyle('backgroundAlpha',0)"
				color="#ffffff"
				>
				<mx:htmlText>
					<![CDATA[1.This demo shows the usage of the classes JPEGEncoder and PNGEncoder
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".]]>
				</mx:htmlText>
			</mx:TextArea>
		</mx:Canvas>

		<mx:ControlBar>
			<mx:CheckBox id="isCorelib" label="use core lib encoders (unchecked) or adobe encoders (checked)?"/>
			<mx:Button label="save to JPG image" click="save('JPG');"/>
			<mx:Button label="save to PNG image" click="save('PNG');"/>
			<mx:Button label="save to BMP image" click="save('BMP');"/>
		</mx:ControlBar>
	</mx:Panel>

</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 Follow us Follow us
You can leave a response, or trackback from your own site.

6 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 :)

  3. martha says:

    thanks a lot for the code… bravo! ^^

  4. Giacomo says:

    I’m using Flash Builder 4.5, writing a AS Mobile Project with Flex 4.5 SDK as default SDK and Air 2.5 Runtime forced. I’m not allowed to import mx.graphics.* as well as com.adobe.images.*
    What could be the issue?

    Thank you in advance.
    GM

  5. JPGEncoder, i thing before that converting the BitMap data to JPEG is a very easy thing, but i am wrong there will be a great study and review to make it. Thanks for the codes tutorial it will be easier to learn converting image because of that.

Leave a Reply