how to get a function to activate which is ment to be used with - actionscript-3

I have this code were I take from a external XML file a Link of an Image load it with ...
<mx:Label
id="textboxLink" text=""/>
private function loadRemoteImg(url:String):void {
textboxLink.text
.....
loader, completeHandler etc.
Save Image(), with ByteArray, JPEGEcoder and then to the location - filestream etc.
This works all fine yet it is only possible (due to supposedly Flash Player 10 onwards) by MouseEvent so of a Click of a button!
As mentioned it works all fine, but I really would need this to activate on start up like in a creationComplete or else!
Any help or any ideas would be appriciated! regards aktell

Ah, sorry, I thought you were just trying to load the image; I didn't see that you were trying to save it as well.
For both of the following cases, you'll need to load the image as Binary:
var urlLoader:URLLoader = new URLLoader(new URLRequest( myURL ));
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
...
This is because if we load it normally (using a Loader), then what we'll get is a Bitmap object, i.e. Flash's representation of your image, rather than the jpg/png data itself. Loading it using this method will give you a ByteArray when it's loaded.
If you're using AIR, you should be able to use the FileStream class: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/filesystem/FileStream.html
Something like:
// NOTE: you can use any of the other File constants to get your path (e.g.
// documentsDirectory, desktopDirectory...
// myImageFileName is the name of your image, e.g. "myPic.jpg"
var file:File = File.applicationStorageDirectory.resolvePath( myImageFileName );
var fs:FileStream = new FileStream;
try
{
fs.open( file, FileMode.WRITE );
fs.writeBytes( imageBinaryData ); // imageBinaryData is a ByteArray
fs.close();
}
catch ( e:Error )
{
trace( "Can't save image: " + e.errorID + ": " + e.name + ": " + e.message );
}
If you're using Flash, then the only way you can save something without user interaction, is through a SharedObject. This will mean that you data won't be available outside the app (it'll be a .sol file), but depending on how you're doing it, this might not be a problem.
// get our shared object - if you're saving a lot of images, then you might need another shared
// object, whose name you know, that stores the names of the other images
var so:SharedObject = null;
try { so = SharedObject.getLocal( this.m_name ); }
catch ( e:Error )
{
trace( "Couldn't get shared object: " + e.errorID + ": " + e.name + ": " + e.message );
return;
}
// NOTE: it's possible you may need a registerClassAlias on the ByteArray before this
so.data["image"] = imageBinaryData;
// save the lso
try { so.flush( minDiskSpace ); }
catch ( e:Error )
{
trace( "Couldn't save the lso: " + e.errorID + ": " + e.name + ": " + e.message );
}
To actually use your image later, load your file(in binary mode)/get your SharedObject, and convert the saved binary to an image:
var l:Loader = new Loader;
l.contentLoaderInfo.addEventListener( Event.COMPLETE, this._onConvertComplete ); // you could probably also listen for the IO_ERROR event
try
{
// NOTE: you can pass a LoaderContext to the loadBytes methods
l.loadBytes( imageBinaryData );
}
catch( e:Error )
{
trace( "Couldn't convert image: " + e.errorID + ": " + e.name + ": " + e.message );
}
...
// called when our loader has finished converting our image
private function _onConvertComplete( e:Event ):void
{
// remove the event listeners
var loaderInfo:LoaderInfo = ( e.target as LoaderInfo );
loaderInfo.removeEventListener( Event.COMPLETE, this._onConvertComplete );
// get our image
var bitmap:Bitmap = loaderInfo.content;
this.addChild( bitmap );
}
If you can't use any of those methods, then you're going to have to have some sort of user interaction (e.g. mouse click). (Out of curiosity, have you tried just dispatching a MouseEvent.CLICK on the relevant object, to see if it would work?)

Related

Animate 2021 Action Script 3 URLRequest causes Error 2035

I'm working on an application and we are using Flash to add an interface. During the initialize the app loads in a config file with references to image paths. When I use the Loader and URLRequest classes to load those images the path is not working and it's causing issues. Based on everything I've researched my code should work. I have a trace that outputs "source/icons/default.png" which is the correct relative path for the external image and loading the image works, but I need to use a variable to set the image path. Setting the URLRequest with a variable, new URLRequest("source/icons/" + default.png);, causes it use a full file path that looks wrong and reports a 2035 error. Is there something that I'm doing wrong? I'm not sure what to do at this point. I've verified the file exists and I've verified the path of the file.
Trace Ouput:
source/icons/default.png
Error Output:
[CompanionStatus] Error occurred while loading bitmap
[CompanionStatus] 2035 : Error #2035: URL Not Found. URL: file:///C|/Users/devtrooper/Desktop/project/source/icons/default.png
It looks like flash is replacing the colon (:) near the drive letter with a pipe (|) and I'm not sure if that is the issue.
Here is my method for loading images:
private function getBitmapData(nameString:String, imagePath:String):void{
try{
var bitmapDataFunction:Function = addBitmapDataToDictionary(nameString);
var path:String = ICON_FOLDER_PATH + imagePath;
var loader:Loader = new Loader();
var urlRequest:URLRequest = new URLRequest("source/icons/" + imagePath);
trace("URLRequest.url " + urlRequest.url);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, bitmapDataFunction, false, 0, true);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, handleBitmapDataError, false, 0, true);
loader.load(urlRequest);
} catch (e:Error) {
log("Error occured while trying to load image data");
log(e.name + " : " + e.message);
}
}
you can use File method instead of urlRequest method like this:
var urlPath:String="";
var picFile:File = File.desktopDirectory.resolvePath("source/icons/default.png");//you can use applicationDirectory,applicationStorageDirectory,userDirectory,doumenntDirectory and ...
if (picFile.exists == true) {
urlPath = picFile.url;
}

In AS3, load a text file into a string

I've been trying to load a text file into a string variable. The text file named text.txt containing successful. Here's the code:
public class Main extends Sprite
{
private var text:String = "text";
private var textLoader:URLLoader = new URLLoader();
public function Main() {
textLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void {
trace("Before 1: " + text); //output: text
trace("Before 2: " + e.target.data); //output: successful
text = e.target.data;
trace("After 1: " + text); //output: successful - yay!!! it worked
}
textLoader.load(new URLRequest("text.txt"));
trace("After 2: " + text); //output: text - what??? nothing happened??? but it just worked
}
}
Output:
After 2: text
Before 1: text
Before 2: successful
After 1: successful
You are facing a synchronous vs asynchronous problem
The function onLoaded is called asynchronously by textLoader when Event.COMPLETE is dispatched, as opposed to "After 2" which is called directly after textLoader.load.
What you must keep in mind is textLoader.load is non-blocking which means "After 2" is probably (you can assume always) executed before onLoaded.
If at this point of the answer you're still confused, I'd say that loading a file takes time and executing an instruction may vary in time but is mostly infinitely shorter than it takes to load a file (imagine this file is 4go large). You cannot predict what will happen, maybe the disk is already very busy you may need to wait! But you could use this precious time to do something else totally independant from the text file, and that is why it is sometimes made asynchronously by programming languages (php for example loads a file synchronously).
Next step
Now that I have explained that "After 2" does not really exist, you have to use "After 1"
as an entry point but nothing helps you from making a function named afterLoad which you would call like this
public function Main() {
textLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void {
trace("Before 1: " + text); //output: text
trace("Before 2: " + e.target.data); //output: successful
text = e.target.data;
afterLoad();
}
textLoader.load(new URLRequest("text.txt"));
}
}
private function afterLoad():void {
trace("After: " + text); // it should work now :)
}

as3 file download restrain?

I have a flash download on my site to download a pdf file.
var myfileReference:FileReference = new FileReference();
down_mc.visible = false;
down_comp.visible = false;
var myRequest:URLRequest = new URLRequest("GEORGIA INCORPORATED.pdf");
myfileReference.addEventListener(IOErrorEvent.IO_ERROR, ioError);
output_txt.text = "";
function ioError(event:ErrorEvent):void {
output_txt.text = "Sorry that there is an IO error during the file downloading. The error is:" + "\n" + event;
}
myfileReference.addEventListener(ProgressEvent.PROGRESS, fileDownloadProgress);
function fileDownloadProgress(event:ProgressEvent):void {
down_mc.visible = true;
}
myfileReference.addEventListener(Event.COMPLETE, fileDownloadCompleted);
function fileDownloadCompleted(evt:Event):void {
down_mc.visible = false;
down_comp.visible = true;
}
function downloadFile (event:MouseEvent):void {
try {
myfileReference.download(myRequest);
} catch (error:SecurityError) {
downloading. The error is:" + "\n" + error;
} catch (error:IllegalOperationError) {
downloading. The error is:" + "\n" + error;
}
}
b1.addEventListener(MouseEvent.CLICK, downloadFile);
the problem is some people want to change the name of the file they are downloading and changing the extension as well, the .pdf , thus making the file unusable. is there any way to restrain the clients from changing the extension?
In pure as3, you cannot force user to save a file under a specific extention. The only way to do it should be to use Air that let you have control on it through a FileStream Object (you can choose file name).
If you want to do it with Air, then you can do :
// Assuming you get your pdf raw data
var pdfData : ByteArray;
var f : File = File.desktopDirectory.resolvePath("myPdf.pdf");
// When user have select a file
f.addEventListener(Event.SELECT, function(e:Event):void{
var targetFile : File = e.target as File;
// Check if the selected file have pdf extension
if(targetFile.nativePath.substr(targetFile.nativePath.length - 4) != ".pdf")
// If not, add it
targetFile = new File(targetFile.nativePath + ".pdf");
// Save the file
var fs : FileStream = new FileStream();
fs.open(targetFile, FileMode.WRITE);
fs.writeBytes(pdfData);
fs.close();
});
// Ask user to save a file (by default on user desktop)
f.browseForSave("Save PDF");

I am trying to load a facebook profile picture with Loader()

I'm having trouble passing the url for a users facebook profile picture to a Loader() variable. I'm using a PHP file to get around the security and from the debug I made, it shows that I'm getting the URL fine, but the Loader runs the error event listener. Here is what my facebookProxy.php file looks like;
<?php
$path=$_GET['path'];
header("Content-Description: Facebook Proxied File");
header("Content-Type: image");
header("Content-Disposition: attactment; filename =".$path);
#readfile($path);
?>
and here is my code for loading the url then loading the image.
function LoadMyPicture():void
{
debug.text = "Entered loadMyPicture() function";
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, MyPictureLoaded, false, 0, true);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, MyPictureLoadError, false, 0, true);
var request:URLRequest = new URLRequest("facebookProxy.php");
var variables:URLVariables = new URLVariables();
variables.path = Facebook.getImageUrl(Facebook.getSession().uid);
request.data = variables;
loader.load(request);
addChild(loader);
debug.appendText(" \nURLRequest url: " + request.url);
debug.appendText(" \nURLRequest data: " + request.data);
debug.appendText(" \n" + loader.content);
}
function MyPictureLoaded(e:Event):void
{
debug.appendText(" \nEntering MyPictureLoaded");
var loader:Loader = e.target.loader;
var bitmap = Bitmap(loader.content);
bitmap.smoothing = true;
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, MyPictureLoaded);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, MyPictureLoadError);
debug.appendText(" \nLoader Content: " + loader.content);
//Note: picturePlaceholder is just a blank movie clip on the Stage
bitmap.width = picturePlaceHolder.width;
bitmap.height = picturePlaceHolder.height;
picturePlaceHolder.addChild(bitmap);
debug.appendText(" \nBitmap width: " + String(bitmap.width) +
" \nBitmap height: " + String(bitmap.height))
}
function MyPictureLoadError(e:Event):void
{
debug.appendText(" \nMyPictureLoadError: Loader Error!");
}
debug.appendText(" \nURLRequest url: " + request.url);
debug.appendText(" \nURLRequest data: " + request.data);
debug.appendText(" \n" + loader.content);
These lines show as follows;
URLRequest url: facebookProxy.php
URLRequest data: path=https%3A%2F%2Fgraph%2Efacebook%2Ecom%2F100001902730917%2Fpicture
null
So the content in the loader is null, how would I debug this? Does anyone have any solutions that could help me?
EDIT
I forgot to mention that I followed a tutorial to that did not explain any of the basics about the code that they provided, so I'm fairly lost to the concept of the loader. This is the tutorial I followed Loading Facebook profile picture into Flash SWF using open graph api.
The line
debug.appendText(" \n" + loader.content);
occurs outside of the Event.COMPLETE handler.
I would add more listeners for the open, progress, and httpStatus events. The httpStatus event should be very helpful.
Can you add some debugging in your facebookProxy.php?
I was able to figure this out. The variables.path and request.data together with the facebookProxy.php wasn't necessary at all.
After changing the
var request:URLRequest = new URLRequest("facebookProxy.php");
to
var request:URLRequest = new URLRequest(Facebook.getImageUrl(Facebook.getSession().uid, large));
loader.load(request);
picturePlaceHolder.addChild(loader);
Removing
var variables:URLVariables = new URLVariables();
variables.path = Facebook.getImageUrl(Facebook.getSession().uid);
request.data = variables;
Allowed the picture to load properly. It's hard to find an up to date tutorial for all of this, why is that? but I guess I would have to open up a new question to find out lol.

Adobe AIR and different OS filesystems

Another Adobe Air question for you but first here some background into the project I have been tasked with. It is an AIR app that will read assets from a USB key and must work on both WIN and MacOS. The problem is, how do I load assets into the app on MacOS! Sounds simple enough and works seamlessly on Windows.
Here is a code snippet of what i am trying to do:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ok);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
var p:String;
if (os == "mac")
{
p = "/Volumes/" + keyVolume.rootDirectory.name + File.separator + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg";
}
else
{
p = keyVolume.rootDirectory.name + File.separator + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg";
}
var temp:File = new File(p);
Debugger.Display.text += "\nAttempting to load: " + p;
Debugger.Display.text += "\nDoes it exist? " + temp.exists;
loader.load(new URLRequest(p));
... the variable OS and keyVolume are being successfully set in earlier code. Also, I have the event listener callbacks defined as well for ok() and ioErro().
When this is run it prints out on windows:
Attempting to load: G:\0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg
Does it exist: true
... and then successfully loads the asset.
On MacOS, it prints out:
Attempting to load: /Volumes/AC/0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg
Does it exist: true
... and then fails with an IOError every time.
Can anyone see something that I am missing here? Do I have some sort of permission error or something (file has "read / write" access). The USB key is formatted in MS-DOS FAT32, could that be a problem?
EDIT
I formatted a new USB key in MacOS to FAT16 and put the files onto it with no success. Problems remain.
EDIT
I am now just trying to load an asset from /users/-USERNAME-/Desktop and still am receiving the same error, so it looks like it isn't a permissions issue on just the USB stick, it is more widespread than that.
EDIT
PROBLEM SOLVED! I finally worded my Google search correctly and it revealed the answer.
These changes will fix the problem:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ok);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
var p:String = keyVolume.rootDirectory.nativePath + ((os == "mac") ? File.separator : "") + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg";
var temp:File = new File(p);
Debugger.Display.text += "\nAttempting to load: " + temp.url;
Debugger.Display.text += "\nDoes it exist? " + temp.exists;
loader.load(new URLRequest(temp.url));
I have also refined the logical statement involving the OS detection a bit as well.
I hope someone finds this useful!
PROBLEM SOLVED! I finally worded my Google search correctly and it revealed the answer.
These changes will fix the problem:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ok);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
var p:String = keyVolume.rootDirectory.nativePath + ((os == "mac") ? File.separator : "") + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg";
var temp:File = new File(p);
Debugger.Display.text += "\nAttempting to load: " + temp.url;
Debugger.Display.text += "\nDoes it exist? " + temp.exists;
loader.load(new URLRequest(temp.url));
I have also refined the logical statement involving the OS detection a bit as well.
I hope someone finds this useful!