Adobe
Products

Top destinations

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • SiteCatalyst
  • Students
  • Elements family

Adobe Creative Cloud

  • What is Adobe Creative Cloud?
  • Design
  • Web
  • Photography
  • Video
  • Students
  • Teams
  • Enterprise
  • Educational institutions

Design and photography

  • Photoshop
  • Illustrator
  • InDesign
  • Adobe Muse
  • Lightroom

Video

  • Adobe Premiere
  • After Effects

Web development and HTML5

  • Edge Tools & Services [opens in a new window]
  • Dreamweaver
  • Gaming [opens in a new window]

Adobe Marketing Cloud

  • What is Adobe Marketing Cloud?
  • Digital analytics
  • Social marketing
  • Web experience management
  • Testing and targeting
  • Media optimization

Analytics

  • SiteCatalyst
  • Adobe Discover
  • Insight

Social

  • Adobe Social

Experience Manager

  • CQ
  • Scene7

Target

  • Test&Target
  • Recommendations
  • Search&Promote

Media Optimizer

  • AdLens
  • AudienceManager
  • AudienceResearch

Document services

  • Acrobat
  • EchoSign [opens in a new window]
  • FormsCentral [opens in a new window]
  • SendNow [opens in a new window]
  • Acrobat.com [opens in a new window]

Publishing

  • Digital Publishing Suite

  • See all products
Business solutions

By business need

  • Digital analytics
  • Digital publishing
  • Document management
  • Media optimization
  • Social marketing
  • Testing and targeting
  • Video editing and serving
  • Web development [opens in a new window]
  • Web experience management
  • See all business needs

By industry

  • Broadcast
  • Education
  • Financial services
  • Government
  • Publishing
  • Retail
  • See all industries
Support & Learning

I need help

  • Products
  • Adobe Creative Cloud
  • Adobe Marketing Cloud
  • Forums [opens in a new window]

I want to learn

  • Training and tutorials
  • Certification [opens in a new window]
  • Adobe Developer Connection
  • Adobe Design Center
  • Adobe TV [opens in a new window]
  • Adobe Marketing Center
  • Adobe Labs [opens in a new window]
Download
  • Product trials
  • Adobe Flash Player
  • Adobe Reader
  • Adobe AIR
  • See all downloads
Company
  • Careers at Adobe
  • Investor Relations
  • Newsroom
  • Privacy
  • Corporate Social Responsibility
  • Customer Showcase
  • Contact us
  • More company info
Buy
  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers
  • Adobe Marketing Cloud sales [opens in a new window]
Search
 
Info Sign in
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Welcome,
My Adobe
My orders
My information
My preferences
My products and services
Sign out
My cart
Privacy My Adobe
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out Privacy My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Promotions
Estimated shipping
Tax
Calculated at checkout
Total
Review and Checkout
Adobe Developer Connection / Adobe AIR Developer Center /

Uploading images from CameraRoll and CameraUI

by Joe Ward

Joe Ward

Content

  • Getting the media promise
  • Getting the raw image data
  • Uploading the image
  • Where to go from here

Created

15 August 2011

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScriptAdobe AIRmobile
Was this helpful?
Yes   No

By clicking Submit, you accept the Adobe Terms of Use.

 
Thanks for your feedback.

Requirements

Prerequisite knowledge

General experience of building AIR applications with Flash Builder, Flash Professional, or other tools is suggested.

User level

Intermediate

Required products

  • Adobe AIR
  • Flash Builder (Download trial)
  • Flash Professional (Download trial)

Sample files

  • media_promise_upload.zip

This article discusses how to upload images obtained via the CameraRoll and CameraUI classes to a server.

The CameraRoll class lets you open an image browser so that the user can select a picture from the device media library. The CameraUI class lets you launch the device camera app so that the user can take a picture or video. In both cases the CameraRoll and CameraUI objects return the media via an event containing a media promise.

The options available for accessing the data in a media promise are different from one platform to another. For example, on Android, the media promise includes a file property that references the source image file, but on iOS this property is always null—the source file is not accessible. The technique described in this article works on all platforms.

Getting the media promise

The first step is to request the image from either the CameraRoll or the CameraUI object. In both cases, you create the appropriate object, set up some event listeners, and then call the function that asks for the image. The runtime then returns the image in an event containing the media promise after the user has either chosen a picture from the device media library or taken a new picture with the camera.

CameraRoll

The following code example sets up the event listeners necessary to handle the events that can be dispatched by a CameraRoll object and then calls the browseForImage() method. When the user selects an image, the runtime calls an event handler function named, imageSelected.

//declare cameraRoll where it won't go out of scope var cameraRoll:CameraRoll = new CameraRoll(); if( CameraRoll.supportsBrowseForImage ) { cameraRoll.addEventListener( MediaEvent.SELECT, imageSelected ); cameraRoll.addEventListener( Event.CANCEL, browseCanceled ); cameraRoll.addEventListener( ErrorEvent.ERROR, mediaError ); cameraRoll.browseForImage(); } else { trace( "Image browsing is not supported on this device."); }

CameraUI

The code for requesting an image from the CameraUI object is very similar:

private var cameraUI:CameraUI = new CameraUI(); if( CameraUI.isSupported ) { trace( "Initializing..." ); cameraUI.addEventListener( MediaEvent.COMPLETE, imageSelected ); cameraUI.addEventListener( Event.CANCEL, browseCanceled ); cameraUI.addEventListener( ErrorEvent.ERROR, mediaError ); cameraUI.launch( MediaType.IMAGE ); } else { trace( "CameraUI is not supported."); }

One difference to note is that the CameraRoll dispatches an event of type MediaEvent.SELECT and the CameraUI class dispatches an event of type MediaEvent.COMPLETE.

Getting the raw image data

You can get the raw image data from the media promise as a byte array. A media promise object is allowed to provide its data in a few different ways, though. So, it takes a bit of care to create a robust, cross-platform solution. On Android, the media promise dispatched by CameraRoll and CameraUI includes a File object referencing the image file. However, the File object is not available on iOS. If your code opens the file directly, it will only work on Android.

If you just want to display an image, you can always use the Loader.loadMediaPromise() method. This method loads and decodes the image as a display object. But to upload the image, you need either a File object or a ByteArray object containing the image data, not a Flash display object. You can use the file property of the MediaPromise object when it is available, but when a file property is not available, you can access the image data by reading the media promise data source.

A media promise object provides access to a data source that can be synchronous or asynchronous. In the synchronous case, you can open the data source and read the data immediately. But in the asynchronous case, you must wait for progress or complete events before the data is available.

The following code example checks to see whether the media promise data source is synchronous or asynchronous (using the isAsync property). In the asynchronous case, the example adds an event listener. Because you don't know what type of object the actual data source is, you have to cast it to the appropriate interface using the "as" operator. Cast the object to the IDataInput interface to read data from the data source. Cast it to the IEventDispatcher interface to access the addEventListener() method of an asynchronous data source.

private var dataSource:IDataInput; private function imageSelected( event:MediaEvent ):void { trace( "Media selected..." ); var imagePromise:MediaPromise = event.data; dataSource = imagePromise.open(); if( imagePromise.isAsync ) { trace( "Asynchronous media promise." ); var eventSource:IEventDispatcher = dataSource as IEventDispatcher; eventSource.addEventListener( Event.COMPLETE, onMediaLoaded ); } else { trace( "Synchronous media promise." ); readMediaData(); } } private function onMediaLoaded( event:Event ):void { trace("Media load complete"); readMediaData(); } private function readMediaData():void { //do something with the data }

Uploading the image

The easiest way to upload the image is to use FileReference.upload(). Yes, I know I just told you not to rely on the existence of a file. However, you can create a temporary file yourself if you don't get one from the media promise directly. Another benefit to using FileReference.upload() is that it performs a multipart-form-style upload. Many server-side upload scripts expect this type of upload since it is commonly used by HTML forms that allow users to upload files.

The other option is to use the URLLoader class to upload the byte array directly. Performing an upload as a raw byte array is also fairly easy. If your server script expects a multipart form upload, however, you will have to write the code that creates the request into the proper format. Other than FileReference.upload(), there aren't any ActionScript APIs that help you directly. There are third-party libraries that you might be able to use, such as Eugene Zatepyakin's open source MultipartURLLoader class.

FileReference.upload()

The following example illustrates how to create and upload a temporary file: 

private function readMediaData():void { var imageBytes:ByteArray = new ByteArray(); dataSource.readBytes( imageBytes ); tempDir = File.createTempDirectory(); var now:Date = new Date(); var filename:String = "IMG" + now.fullYear + now.month + now.day + now.hours + now.minutes + now.seconds + ".jpg"; var temp:File = tempDir.resolvePath( filename ); var stream:FileStream = new FileStream(); stream.open( temp, FileMode.WRITE ); stream.writeBytes( imageBytes ); stream.close(); temp.addEventListener( Event.COMPLETE, uploadComplete ); temp.addEventListener( IOErrorEvent.IO_ERROR, ioError ); try { temp.upload( new URLRequest( serverURL ) ); } catch( e:Error ) { trace( e ); removeTempDir(); cameraUI.launch( MediaType.IMAGE ) } } private function removeTempDir():void { tempDir.deleteDirectory( true ); tempDir = null; }

You can use this PHP script example given in the ActionScript 3 Developer's Guide to test the upload function. (Remember to increase the maximum file size defined in the script to accommodate the images produced by your device camera.)

URLLoader

If you have control of the server-side script that accepts the image upload, you can upload the image bytes directly without creating a temporary file. On iOS, this can save some memory since there are potentially fewer copies of the image data in memory than otherwise. But as with any optimization, you should evaluate whether the expected gains are worth the effort.

The following function uploads an image as a byte array:

public function upload( data:ByteArray, destination:String, fileName:String = null ):void { if( fileName == null ) //Make a name with correct file type { var type:String = sniffFileType( buffer ); var now:Date = new Date(); fileName = "IMG" + now.fullYear + now.month +now.day + now.hours + now.minutes + now.seconds + ".jpg"; } loader = new URLLoader(); loader.dataFormat= URLLoaderDataFormat.BINARY; var urlString:String = destination + "?file=" + fileName; var request:URLRequest = new URLRequest( urlString ); request.data = data; request.method = URLRequestMethod.POST; request.contentType = "application/octet-stream"; loader.addEventListener( Event.COMPLETE, onUploadComplete ); loader.addEventListener(IOErrorEvent.IO_ERROR, onUploadError ); loader.load(request); }

You can find the code for this function in the Uploader class in the example files. You can test the function with the following simple PHP script:

<?php if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) { $flux = $GLOBALS["HTTP_RAW_POST_DATA"]; $fp = fopen('.images/' . $_GET['file'], 'wb'); fwrite($fp, $flux); fclose($fp); } ?>

Where to go from here

This article covers how to get the image data from a media promise object and a couple of easy ways to upload that data to a server. In the wild, your upload function will need to add headers and parameters to conform with a particular photo services API. You can find more information about these network operations, as well as more information about the CameraRoll and CameraUI classes in the ActionScript 3 Developer's Guide and the ActionScript 3 Reference:

  • Uploading files to a server
  • CameraRoll
  • CameraUI

Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

More Like This

  • Developing cross-platform Adobe AIR applications
  • Performance-tuning Adobe AIR applications
  • Using Badger for Adobe AIR applications
  • Building a native extension for iOS and Android – Part 2: Developing the ActionScript library
  • Creating your first Adobe AIR application on Android
  • Using web fonts with Adobe AIR 2.5
  • Signing Adobe AIR applications
  • Using push notifications in AIR iOS apps
  • Building Lupo: A case study in building commercial AIR applications
  • Using the Push Notifications native extension for iOS

Products

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • Digital Publishing Suite
  • Elements family
  • SiteCatalyst
  • For education

Download

  • Product trials
  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR

Support & Learning

  • Product help
  • Forums

Buy

  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2013 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy | Cookies

Ad Choices

Reviewed by TRUSTe: site privacy statement