Leave That Thing Alone Blog

Viewing Camera RAW Images with ColdFusion

This example demonstrates how to open/save/view Camera RAW images with ColdFusion and jrawio. jrawio is a Service Provider Implementation for the java ImageIO it provides the ability to read camera raw image formats such as Canon CR2/CRW and Nikon NEF. Check the jrawio site for a list of currently supported cameras.

Setup jrawio

The first step is to download the jrawio binary.
Take the jar (it.tidalwave.imageio.raw-[version].jar) and place it in ColdFusion's "\lib\" directory.

Read RAW image and write to JPG

This first example reads a camera raw file and converts it to a JPG and writes it to a file. The benefit of writing the file as a JPG is that this process is relatively fast.

<cfscript>
	//input file
	filename = expandPath("CRW_3933.CRW");
	fileio = createObject("Java","java.io.File").init(filename);
	//read RAW
	imageio = createObject("Java","javax.imageio.ImageIO").read(fileio);
	//write jpg
	outname = expandPath("CRW_3933.jpg");
	output = createObject("Java","java.io.File").init(outname);
	createObject("Java","javax.imageio.ImageIO").write(imageio, "jpg", output);
</cfscript>

Read RAW image, resize, and writetobrowser

This next example reads a camera raw image, resizes the image to a thumbnail, then writes that image to browser. Warning this can be very slow.

<cfscript>
	//input file
	filename = expandPath("CRW_3933.CRW");
	fileio = createObject("Java","java.io.File").init(filename);
	//read RAW
	imageio = createObject("Java","javax.imageio.ImageIO").read(fileio);
	//resize
	imageWidth = 200;
	imageHeight = 200;
	scaledImage = imageio.getScaledInstance(JavaCast("int", imageWidth), JavaCast("int", imageHeight), imageio.SCALE_FAST);
	bufferedImage = createObject("java", "java.awt.image.BufferedImage").init(JavaCast("int", imageWidth), JavaCast("int", imageHeight), imageio.TYPE_INT_RGB);
	graphics = bufferedImage.createGraphics();
	graphics.drawImage(scaledImage, 0, 0, Javacast("null", ""));
	//create cfimage from buffered image
	cfimage = imageNew(bufferedImage);
</cfscript>

<cfimage action="writeToBrowser" source="#cfimage#">

Can be slow...

Be aware that processing of RAW images can be very slow and processor intensive. For example the second code sample may take 10-30 seconds with a large raw image.

Flex 4 Custom Preloader

In this example were going to look at a way to create a custom preloader SWC in Flash Professional and use it inside of a Flex 4 application by extending the SparkDownloadProgressBar class.
This preloader will display the progress percentage of loading and also a count of RSLs as they are being loaded, after loading is complete the progress of initialization will be displayed. Both of the progresses will be displayed by a graphical progress bas and in text.

View Demo Preloader App (right click for source view)

The preloader may fly by, so lets first take a look at how this progress bar looks as it is loading the Flex app:
flex 4 preloader

The next screenshot shows the progress as RSLs are being loaded:
flex 4 preloader

Finally the progress of initialization, with a second progress bar:
flex 4 preloader

Creating the Preloader SWC in Flash Pro

In Flash professional we create a custom preloader. In this example there are several layers which the design is created from. The layer 'prog_bar' and 'initilize_bar" hold shapes that we will use to resize to show progress. The 'loading text' layer contains some dynamic text that has Character Embedding for upper/lower/numbers. The layers look like this:

flex 4 preloader

The custom preloader FLA can be found in the example by viewing source.

The FLA preloader is a movie clip and its properties are set for "Export for ActioScript" the "Class" property is set to "PreloaderDisplay" this allows us to have a PreloaderDisplay.swc created when this FLA is published.

flex 4 preloader

In the first frame of the FLA "actions" layer we create the functions to set the two different progress bars:

//reset
setMainProgress(0);
setInitalizeProgress(0);
loading_txt.text = "";

//function for setting main prgress bar function setMainProgress(percent:Number):void { prog_bar.width = percent * 275; }

//function for setting the initilize bar function setInitalizeProgress(percent:Number):void { initialize_bar.width = percent * 275; }

The final step is to "Publish" the FLA so that the SWC file is create, this SWC will be used in Flash Builder.

Creating the Custom Preloader in Flex 4

The first step is to place the PreloaderDisplay.swc in the "libs" folder, this will make the PreloaderDisplay and its methods available to Flex:

preloader swc libs

To define a custom preloader we will do this in the Flex application's Application file, we simply specify the preloader class:

<s:Application preloader="com.themorphicgroup.preload.Preloader" ...

In the Preloader class we will extend "SparkDownloadProgressBar". The SparkDownloadProgressBar class displays download progress.
From Flex 4 docs: It is used by the Preloader control to provide user feedback while the application is downloading and loading. The download progress bar displays information about two different phases of the application: the download phase and the initialization phase.

The Preloader.as extends "SparkDownloadProgressBar" and we will use the FLA PreloaderDisplay.swc by creating a variable called "preloaderDisplay":

public class Preloader extends SparkDownloadProgressBar {
	private var preloaderDisplay:PreloaderDisplay;
	...

To add the PreloaderDisplay we will override the SparkDownloadProgressBar's "createChildren" method, in this method we will create a new PreloaderDisplay and use the "addChild" method (SparkDownloadProgressBar inherits addChild from DisplayObjectContainer):

override protected function createChildren():void
{
	if (!preloaderDisplay) {
		preloaderDisplay = new PreloaderDisplay();
		
		var startX:Number = Math.round((stageWidth - preloaderDisplay.width) / 2);
		var startY:Number = Math.round((stageHeight - preloaderDisplay.height) / 2);
		
		preloaderDisplay.x = startX;
		preloaderDisplay.y = startY;
		addChild(preloaderDisplay);
	}
}

There are several methods that will override so that we can make updates to the PreloaderDisplay.swc. The rslProgressHandler method will be called each time a RSL is being loaded. We will use this method to set text indicating the current count of RSL being loaded:

private var rslBaseText:String = "loading: ";
override protected function rslProgressHandler(evt:RSLEvent):void {
	if (evt.rslIndex && evt.rslTotal) {
		//create text to track the RSLs being loaded
		rslBaseText = "loading RSL " + evt.rslIndex + " of " + evt.rslTotal + ": ";
	}
}

The next method we will override is setDownloadProgress. This method indicates the current download progress. in this method we will set the PreloaderDisplay.swc main progress bar and set the text:

override protected function setDownloadProgress(completed:Number, total:Number):void {
	if (preloaderDisplay) {
		//set the main progress bar inside PreloaderDisplay
		preloaderDisplay.setMainProgress(completed/total);
		//set percetage text to display, if loading RSL the rslBaseText will indicate the number
		setPreloaderLoadingText(rslBaseText + Math.round((completed/total)*100).toString() + "%");
	}
}

Finally we will look at overriding setInitProgress, this method indicates the progress of the Flex app as it initializes. We will set the text in PreloaderDisplay.swc and change the progress of the second initialize progress bar:

override protected function setInitProgress(completed:Number, total:Number):void {
	if (preloaderDisplay) {
		//set the initialization progress bar inside PreloaderDisplay
		preloaderDisplay.setInitalizeProgress(completed/total);
		//set loading text
		if (completed > total) {
			setPreloaderLoadingText("almost done");
		} else {
			setPreloaderLoadingText("initializing " + completed + " of " + total);
		}
	}
}

 

This blog entry does not cover every bit of code used in the preloader, so View Demo Preloader App right click for source view

 

Example of Feature Rich Item Renderers in Flex 4

This is an example of creating feature rich item renderers in Flex 4. The example retrieves this blog's RSS feed and displays each entry in a list. This example will demonstrate:

  • Skinning and item renderer
  • States in an item renderer
  • Pass callback function into item renderer
  • Override ItemRenderer 'set data' have data as a known ValueObject
  • Swap icons/images based on data values


 View the Example with source view enabled

This blog post will cover the main points of the example but not the entire code, so view the example's source view to see all the code in full.

Getting Blog Entries From RSS

I won't go into too much detail about how the data is retrieved, view the source for all the details. The RSSService class makes a request to this blog's RSS url. That XML responce is turned into an ArrayCollection of BlogEntryVO value objects. The result ArrayCollection is set as the data provider for the Spark List.

Skinning the Spark List

Spark List: The first step in skinning the Spark List is to define the 'skinClass':


<s:List id="blogList"
    skinClass="com.themorphicgroup.skins.list.ListSkin"
    change="blogList_selectionHandler(event)"
    caretChange="blogList_selectionHandler(event)" />

Skinning Spark List: Lets look at the 'com.themorphicgroup.skins.list.ListSkin' List skin class. The most important parts of this skin is the 'Scroller' and 'DataGroup' it surrounds. The DataGroup is a simple container class in Flex 4 for holding data items and item renderers. The Scroller enables the DataGroup items to be scrolled. Full List skin code:


<?xml version="1.0" encoding="utf-8"?>
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009"
             xmlns:s="library://ns.adobe.com/flex/spark"
             xmlns:mx="library://ns.adobe.com/flex/halo">


    <fx:Metadata>
        [HostComponent("spark.components.List")]
    </fx:Metadata>
    
    <s:states>
        <s:State name="normal" />
        <s:State name="over"/>
    </s:states>
    
    <!-- background -->
    <s:Rect top="0" right="0" bottom="0" left="0">
        <s:stroke>
            <s:SolidColorStroke color="0x999999" weight="2"/>
        </s:stroke>
        <s:fill>
            <s:SolidColor color="0xffffff" color.over="0xf8f8f8" />
        </s:fill>
    </s:Rect>
    
    <!-- scroller -->
    <s:Scroller id="scroller"
                left="0"
                top="0"
                right="0"
                bottom="0"
                horizontalScrollPolicy="off"
                minViewportInset="1"
                focusEnabled="false">

        
        <!-- container for data-->
        <s:DataGroup id="dataGroup">
            <s:layout>
                <s:VerticalLayout gap="0" horizontalAlign="contentJustify" />
            </s:layout>
        </s:DataGroup>
        
    </s:Scroller>
    
</s:SparkSkin>

Skinning Spark List and global vertical scrollers: The last thing we will look at in skinning the List is the skin for the Scroller (VScroll). The skin classes for the scroller are in com.themorphicgroup.skins.scroller.vertical To define the 'VerticalScrollbar' Skin to all Spark VScrollBar we do that in the css file:


s|VScrollBar {
    skinClass: ClassReference("com.themorphicgroup.skins.scroller.vertical.VerticalScrollbar");
}

Define an ItemRenderer for the Spark List

In creationComplete we will create the item renderer for the Spark List, we will also define any needed properties. In this case we want to pass in a callback funtion for when the delete icon is clicked in an item renderer.


//create itemrenderer
protected function application_creationCompleteHandler(event:FlexEvent):void {
    //create itemrenderer
    blogListItemRenderer = new ClassFactory(BlogEntryItemRenderer);
    //define properties (callback for item delete)
    blogListItemRenderer.properties = {deleteHandlerFunction:itemDeleteClick_handler};
    //set itemrenderer to List
    blogList.itemRenderer = blogListItemRenderer;
    .... }

//callback function for delete click
private function itemDeleteClick_handler(blogEntryItem:BlogEntryVO):void {
    ...

Inside the Item Renderer when the delete icon is clicked the callback function is passed the current item renderer's data (a value object):


public var deleteHandlerFunction:Function;
private function trash_btn_clickHandler(event:MouseEvent):void {
    //callback function pass BlogEntryVO value object
    deleteHandlerFunction(blogEntry);
}

The ItemRenderer

Setting data in the ItemRenderer: In the 'BlogEntryItemRenderer' we will override the the set data function and set a BlogEntryVO with the data of the item renderer:


private var blogEntry:BlogEntryVO

override public function set data(value:Object):void {
    super.data = value;
    if (value is BlogEntryVO) {
        blogEntry = BlogEntryVO(value);
    }
}

Displaying data in the ItemRenderer: To display the data values in the itemrenderer we will override updateDisplayList and set values to Labels etc:


override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
    super.updateDisplayList(unscaledWidth,unscaledHeight);
    
    if (title_lbl) {
        title_lbl.text = blogEntry.title;
        ...

Skinning and States in the ItemRenderer

To make the item renderer more attractive and interactive we will create some states. In Flex 4 you can specify not only the name of a state but a name that will define a group of states:


<s:states>
    <s:State name="normal" />
    <s:State name="hovered" stateGroups="[hoveredStates]" />
    <s:State name="selected" stateGroups="[selectedStates]" />
    <s:State name="normalAndShowsCaret" />
    <s:State name="hoveredAndShowsCaret" stateGroups="[hoveredStates]" />
    <s:State name="selectedAndShowsCaret" stateGroups="[selectedStates]" />
</s:states>

Having the state and stateGroups names means we can define properties for those states. For example with can set the alpha of the background color as alpha='0' and them the when we are in one of the hovered states as alpha.hoveredStates='.1':


<s:Rect width="100%" height="100%">
    <s:fill>
        <s:SolidColor color="0x6699cc" alpha="0" alpha.hoveredStates=".1" alpha.selectedStates=".25" />
    </s:fill>
</s:Rect>

<s:Label id="title_lbl"
         maxDisplayedLines="1"
         styleName="myriad"
         left="10"
         top="10"
         right="26"
         textDecoration.hoveredStates="underline"
         fontWeight.selectedStates="bold"
         color="#000000"
         fontSize="14"/>

Summary

This blog post does not cover every bit of code in the example so View the Example with source view enabled.

ColdFusion devcamp in San Francisco Nov. 7th, 2009

Sign up for cfdevcamp in San Francisco November 7th 2009.

cfdevcamp is a gathering of people passionate about learning through collaboration. Attendees will work in small teams to code projects ideas from the team members or from a suggested list of projects. This will not be a lecture style event or a traditional classroom with a set curriculum and learning materials. We want you to ask questions, hack away and have fun.

This is a great event for ColdFusion beginners, experts, and everyone in between.

For more information and to sign up for this free event visit: www.cfdevcamp.org

ColdFusion Security at Sacramento ColdFusion User Group Oct. 13, 2009

Join the Sacramento ColdFusion User Group Oct. 13, 2009 for a presentation on how to secure your ColdFusion applications and server. We will cover a broad range of topics from preventing SQL injection and cross site scripting attacks, to form validation, server settings, and more.

We will also be doing one of our giant Adobe software giveaways...

More info and directions here: www.saccfug.com

Sean Corfield and Railo at Sacramento ColdFusion User Group

Join the Sacramento ColdFusion User Group on Tuesday June 9th 2009 for Sean Corfield who will be speaking about Railo's CFML engine.

For more details on the meeting visit the SacCFUG website.

CFCPhotoBlog Adds Railo Support

CFCPhotoBlog has been updated to support Railo

There were actually very few changes required to make Railo happy. The main problem was that I had used several Adobe ColdFusion specific cfform tags that were not really needed.

View a demo and download from CFCPhotoBlog project page

 

Example of Feature Rich Dynamic Item Renderers in Flex 3

In the last Flex 3 rich feature item renderer example we looked at item renderers that had some nice visual and functional features, in this example we will take it to the next step and introduce some dynamic abilities to the item renderers. By using dynamic item renderers you can create more flexible & reusable itemrenderers, you can also do neat stuff like pass callback functions to handle events in the itemrenderer.

Here are some of the things this dynamic item renderer example will demonstrate:

  • Reuse the same item renderer for a DataGrid and a List, each with a different data provider
  • Pass delete/click function into item renderer
  • Dynamically change icons
  • Dynamically change the label function
  • Set label title style


View Example (right click for source)

In this post we won't go over every detail of the code, so check out the source in the example.

To start of with the basics, here is how to setup a itemrenderer using ClassFactory:

private var personItemRendererFactory:ClassFactory;
private function onInitialize():void {
	personItemRendererFactory = new ClassFactory(MyItemRenderer);
	peopleColumn.itemRenderer = personItemRendererFactory;
}
...
<mx:DataGrid id="peopleDataGrid" dataProvider="{peopleDataProvider}">
	<mx:columns>
		<mx:DataGridColumn id="peopleColumn" />
	</mx:columns>
</mx:DataGrid>

The example above doesn't really do much more than setting in itemrenderer in the DataGrid tag itself would, so lets set a property of the itemrenderer:

private function onInitialize():void {
	personItemRendererFactory = new ClassFactory(MyItemRenderer);
	personItemRendererFactory.properties = {doStuff: true};
	peopleColumn.itemRenderer = personItemRendererFactory;
}

In the above example we are now creating an itemrenderer and setting the 'doStuff' property using the ClassFactory properties object. Using the class factory properties we can set many things at once including functions. Let's say we want to listen for a click event inside the itemrenderer we can pass in a callback function that gets called from the item renderer when clicked:

private function onInitialize():void {
	personItemRendererFactory = new ClassFactory(MyItemRenderer);
	personItemRendererFactory.properties = {clickFunction: itemrendererClick_handler};
	peopleColumn.itemRenderer = personItemRendererFactory;
}

private function itemrendererClick_handler(evt:MouseEvent):void { Alert.show('clicked'); }

/* this in item renderer */ //inside the itemrenderer we need to define the click function public var clickFunction:Function;

//and then for this example lets call the clickFunction when the canvas is clicked <mx:Canvas click="clickFunction(event)"...

The above example allows a function to set on the itemrenderer. When the itemrenderer is clicked the event is handled in the same component that the holds DataGrid, this can be very convenient.

When using the properties of ClassFactory there is a something to be aware of; your itemrenderer may require a property to be set, but the ClassFactory and properties will not enforce that property to be required. For example if a click handler function is required in the ItemRenderer but not set in the properties there will be a runtime error when the ItemRenderer is clicked.

View the example and right click for source to see more details on how to do things like dynamically change icons and label functions.
View Example (right click for source)

This example is not intended to be a best practices for the most efficient item renderers, for further reading: Efficient Item Renderers, Advanced visual components

Edmund Event-Driven Framework At SacCFUG

Join the Sacramento ColdFusion User Group Tuesday Feb. 10, 2009 for a presentation on the "Edmund" Event-Driven Framework by Patrick Santora.

For more details on the meeting visit the SacCFUG website.

Retrieve Exif Metadata from Camera RAW and TIFF in ColdFusion 8

This example demonstrates how to get Exif metadata from Camera RAW and TIFF files in ColdFusion. In this sample I'm using a raw CR2 file from a Canon D30. Please note this example only reads RAW exif metdata, it does not read/process the RAW image

update: Viewing Camera RAW Images with ColdFusion

ColdFusion 8's image tags allow the retrieval of Exif metadata from only certain image types, ColdFusion actually uses Drew Noakes Metadata Extract library. There is now a beta version (metadata-extractor-2.4.0-beta-1.jar) that introduces code for processing camera RAW images and TIFF files.

One way to use this beta library is to go into the [coldfusion8]\lib\ folder and rename the 'metadata-extractor-2.2.2.jar' file to .bak then copy the latest metadata-extractor JAR file into that directory.

However, in this example i'm going to use Mark Mandel's JavaLoader so I can use the beta library separately from the stable version cfimage uses.

The code below reads a camera Raw image then iterates through all the metadata:

<cfscript>
	//read Canon RAW CR2 file
	photoFile = createObject("java","java.io.File").init("#expandpath('IMG_7913.CR2')#");
	//set the path
	paths[1] = "D:\test\metadata-extractor-2.4.0-beta-1.jar";
	//create the loader
	javaLoader = createObject("component", "JavaLoader").init(paths);
	//create the TiffMetadataReader instace
	tiffMetadataReader = javaLoader.create("com.drew.imaging.tiff.TiffMetadataReader");
	//read metadata
	metadata = tiffMetadataReader.readMetadata(photoFile);
	//get directories
	directories = metadata.getDirectoryIterator();
</cfscript>

<cfoutput> <table cellspacing="0"> <cfloop condition="directories.hasNext()"> <cfset currentDirectory = directories.next() /> <cfset tags = currentDirectory.getTagIterator() /> <cfloop condition="tags.hasNext()"> <cfset currentTag = tags.next()> <tr> <td valign="top">#currentTag.getTagType()#</td> <td style="vertical-align:top;width:150px;">#currentTag.getTagName()#</td> <td valign="top">#currentTag.getDescription()# </td> <td>#currentTag.getTagTypeHex()#</td> </tr> </cfloop> </cfloop> </table> </cfoutput>

Sample output:

coldfusion raw tiff exif

More Entries