Php – Why is JPGEncoded bytearray sent from AS3 to AMFPHP resulting in an invalid image


Im loading images into Flash and using JPGEncoder to encode the image to a ByteArray and send this to AMF PHP which writes out the bytearray to a file. This all appears to work correctly and I can download the resulting file in Photoshop CS4 absolutely fine. When i try to open it from the desktop or open it back in Flash it doesnt work… Picasa my default image browser says "Invalid"

Here is the code i use to write the bytearray to a file –

file_put_contents($filename, $jpg);

That's it … I use the NetConnection class to connect and call the service, do I need to say Im sending jpg data? I assumed that JPGEncoder took care of that. How can I validate the bytearray before writing the file? Do I need to set MIME type or something?

Thanks – here is some code:

function _onImageDataLoaded(evt:Event):void {
  var tmpFileRef:FileReference=FileReference(;
  image_loader=new Loader  ;
  image_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, _onImageLoaded);
function _onImageLoaded(evt:Event):void {
if (bitmap.width>MAX_WIDTH||bitmap.height>MAX_HEIGHT) {
function resizeBitmap(target:Bitmap):void {
    if (target.height>target.width) {
    } else if (target.width >= target.height) {

function uploadResizedImage(target:Bitmap):void {
    var _bmd:BitmapData=new BitmapData(target.width,target.height);
    _bmd.draw(target, new Matrix(target.scaleX, 0, 0, target.scaleY));
    var encoded_jpg:JPGEncoder=new JPGEncoder(90);
    var jpg_binary:ByteArray=encoded_jpg.encode(_bmd);
    _uploadService=new NetConnection();
    _uploadService.connect("http://.../amfphp/gateway.php");"UploadService.receiveByteArray",new Responder(success, error), jpg_binary, currentImageFilename);


Best Solution

Your problem is in your PHP service. In AMFPHP the POST data is abstracted, so what you need in your AMFPHP UploadService script is a function that accepts the two input arguments in your --jpg_binary and currentImageFilename-- like this:

class UploadService {

     function receiveByteArray( $ba, $filename ) {

          $result = file_put_contents($filename, $ba->data);
          if ( $result == FALSE ) {
              trigger_error( "File save failed" );
Related Question