Smooth image on load in as3 - actionscript-3

I am new here and a complete noob when it comes to as3. Somehow I have managed to put this together with some help from different places. And now I turn to you guys :)
I need to put smoothing on my images and thumbs that Im loading from an XML file. I have tried a lot of things but can't get any of it to work and I get this error:
Scene 1, Layer 'as3', Frame 1, Line 27 1120: Access of undefined property e. -> So I know var bitmapContent:Bitmap = Bitmap( e.target.content ); is the problem. but I have no idea what to use instead of e. I
this i what I have so far:
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.None;
import flash.display.Bitmap;
// Loads the first image//
var i =new Loader();
i.load(new URLRequest("images/1.jpg"));
mainLoader.addChild(i)
//Loads the XML file//
var picsXML:XML;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE , xmlLoaded);
xmlLoader.load(new URLRequest("imagelist.xml"));
//Loads images into thumbs//
function xmlLoaded(event:Event):void{
picsXML = new XML(xmlLoader.data);
//trace(picsXML);
var bitmapContent:Bitmap = Bitmap( e.target.content );
bitmapContent.smoothing = true;
var thumbLoader:UILoader;
for (var i:uint=0; i<picsXML.image.length(); i++)
{
thumbLoader=UILoader(getChildByName("thumb"+i));
thumbLoader.load(new URLRequest("thumbs/"+picsXML.image[i].#file));
thumbLoader.buttonMode = true;
thumbLoader.addEventListener(MouseEvent.CLICK, thumbClicked);
thumbLoader.addEventListener(MouseEvent.CLICK, tester);
}
}
//Loads large image when thumb is clicked//
function thumbClicked(event:MouseEvent){
//var bitmapImage:Bitmap = event.target.content;
//bitmapImage.smoothing = true;
var thumbName:String = event.currentTarget.name;
var thumbIndex:uint = uint(thumbName.substr(5));
var fullPath:String = "images/"+picsXML.image[thumbIndex].#file;
mainLoader.load(new URLRequest(fullPath));
var myTween:Tween = new Tween(mainLoader,"alpha", None.easeNone, .3,1,18,false);
}
//Removes the first image when thumbs is clicked//
function tester(event:MouseEvent){
if (mainLoader.contains(i)) {
trace("hej")
mainLoader.removeChild(i);
}
}

If i get your code true problem is here: u import an external xml file which is probably contain your url's and name of pic's. U can't turn ur xml file into a bitmap.
If u want smoothing on your pictures u need to it after load ur pics or thumb's.
Probably ur problem will fix like this :) Hope this will help

Functions with arguments work like this: function Name ( input arg Name : input arg Type )
Firstly, your function xmlLoaded(event:Event) cannot have an input called event
but then you try to do a Bitmap( e.target.content ); so for that bitmap line to work you'd have to change your input name to e like so... xmlLoaded( e : Event );
Secondly, var bitmapContent:Bitmap = Bitmap( e.target.content ); is incorrect.
This is more correct var bitmapContent:Bitmap = img_Bytes_Loader.content as Bitmap; set a Loader's content as Bitmap not XML content (text) as Bitmap (pixels).
Anyways assuming your XML file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Items>
<mp3>
<url> track1.mp3 </url>
<image> image1.jpg </image>
</mp3>
<mp3>
<url> track2.mp3 </url>
<image> image2.jpg </image>
</mp3>
</Items>
Then your code should look something like this below :
var imgLoader_XML : URLRequest;
var picLoader : Loader = new Loader();
function xmlLoaded(event:Event):void
{
picsXML = new XML(xmlLoader.data);
//trace(picsXML);
imgLoader_XML = new URLRequest( picsXML.mp3[ index ].image ); //[index] could be replaced with [i] if FOR loop
picLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, picloadComplete);
picLoader.load (imgLoader_2);
}
public function picloadComplete(evt:Event)
{
yourContainer.addChild(picLoader);
yourContainer.width = 100;
yourContainer.height = 100;
yourContainer.alpha = 1;
}

Thanks for the inputs guys. It is greatly appreciated.
I figured it out. You were right, of course I can't put smoothing on the UILoader, so I had to target the content of the UILoader and run thumbLoader.addEventListener(Event.COMPLETE, smoothing); each time an image is importet.
Here is the entire working code (maybe it can help someone else :) :
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.None;
import flash.display.Bitmap;
import flash.display.Loader;
// Loads the first image//
var i =new Loader();
i.load(new URLRequest("images/1.jpg"));
mainLoader.addChild(i)
//Loads the XML file//
var picsXML:XML;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE , xmlLoaded);
xmlLoader.load(new URLRequest("imagelist.xml"));
//Loads images into thumbs//
function xmlLoaded(event:Event):void{
picsXML = new XML(xmlLoader.data);
var thumbLoader :UILoader = new UILoader();
for (var i:uint=0; i<picsXML.image.length(); i++)
{
thumbLoader=UILoader(getChildByName("thumb"+i));
thumbLoader.load(new URLRequest("thumbs/"+picsXML.image[i].#file));
thumbLoader.buttonMode = true;
thumbLoader.addEventListener(MouseEvent.CLICK, thumbClicked);
thumbLoader.addEventListener(MouseEvent.CLICK, tester);
thumbLoader.addEventListener(Event.COMPLETE, smoothing);
}
}
function smoothing(e:Event):void{
if(e.currentTarget.content is Bitmap)
{
Bitmap(e.currentTarget.content).smoothing = true;
}
}
//Loads large image when thumb is clicked//
function thumbClicked(event:MouseEvent){
var thumbName:String = event.currentTarget.name;
var thumbIndex:uint = uint(thumbName.substr(5));
var fullPath:String = "images/"+picsXML.image[thumbIndex].#file;
mainLoader.load(new URLRequest(fullPath));
mainLoader.addEventListener(Event.COMPLETE, smoothing);
var myTween:Tween = new Tween(mainLoader,"alpha", None.easeNone, .3,1,18,false);
}
//Removes the first image when thumbs is clicked//
function tester(event:MouseEvent){
if (mainLoader.contains(i)) {
trace("hej")
mainLoader.removeChild(i);
}
}

Related

Need help making a button play multiple sounds in Adobe Flash

I'm having an issue trying to get my code work for my Adobe Flash project. Basically I'm trying to get a button to play a random sound everytime it's clicked which works but I can't have that same code on the same frame for a different button which is why it gives me this error.
Here is my code:
import flash.utils.Dictionary;
import flash.events.MouseEvent;
var request:URLRequest = new URLRequest("19103_b.mp3");
var ci_diese:Sound = new Sound();
ci_diese.load(request);
var request_two:URLRequest = new URLRequest("19203_b.mp3");
var d_diese:Sound = new Sound();
d_diese.load(request_two);
var request_three:URLRequest = new URLRequest("19204_b.mp3");
var f_diese:Sound = new Sound();
f_diese.load(request_three);
var play_liste = 0;
var dictSounds = new Dictionary ();
dictSounds[1] = d_diese;
dictSounds[2] = ci_diese;
dictSounds[3] = f_diese;
fireweapon_H3AR.addEventListener (MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler (event:MouseEvent) : void {
play_liste = Math.ceil(Math.random () *3);
dictSounds[play_liste].play ();
ready_H3AR.addEventListener (MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler (event:MouseEvent) : void {
play_liste = Math.ceil(Math.random () *3);
dictSounds[play_liste].play ();}
}
import flash.utils.Dictionary;
import flash.events.MouseEvent;
var request:URLRequest = new URLRequest("Readya.mp3");
var ci_diese2:Sound = new Sound();
ci_diese2.load(request);
var request_two:URLRequest = new URLRequest("Readyb.mp3");
var d_diese2:Sound = new Sound();
d_diese2.load(request_two);
var request_three:URLRequest = new URLRequest("Readyc.mp3");
var f_diese2:Sound = new Sound();
f_diese2.load(request_three);
var play_liste = 0;
var dictSounds = new Dictionary ();
dictSounds[1] = d_diese2;
dictSounds[2] = ci_diese2;
dictSounds[3] = f_diese2;
ready_H3AR.addEventListener (MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler (event:MouseEvent) : void {
play_liste = Math.ceil(Math.random () *3);
dictSounds[play_liste].play ();}
}
Any way to rewrite this to accommodate more than one button? The first half works up until it repeats itself at "import flash." I've been searching everywhere for answers so please help!!
You should not name two functions or two variables the same, because the last ones are going to overwrite the first ones.
For example
var request:URLRequest = new URLRequest("19103_b.mp3");
is then overwritten
var request:URLRequest = new URLRequest("Readya.mp3");
The same happens with the button ready_H3AR an the function listener mouseDownHandler
By the way, you don't need to import the classes twice:
import flash.utils.Dictionary;
import flash.events.MouseEvent;
Usually when a task or a block of code is intended to be used many times, it's better to put it in a function to get a simpler and more maintainable code.
So you can do like this :
var sounds:Array = [
['01.mp3', '02.mp3', '03.mp3'], // sounds for the 1st button
['04.mp3', '05.mp3', '06.mp3'] // sounds for the 2nd button
];
var sound:Sound,
sound_channel:SoundChannel = new SoundChannel();
function play_sound(sound_name:String): void
{
var request:URLRequest = new URLRequest('mp3/' + sound_name);
sound = new Sound();
sound.addEventListener(Event.COMPLETE, on_sound_loaded);
sound.load(request);
}
function on_sound_loaded(e:Event): void
{
// if you want, you can stop the current playing sound
// otherwise you don't need the SoundChannel
sound_channel.stop();
sound_channel = Sound(e.target).play();
}
button_01.addEventListener(MouseEvent.MOUSE_DOWN, on_press);
button_02.addEventListener(MouseEvent.MOUSE_DOWN, on_press);
function on_press(e:MouseEvent): void
{
// to get values : 0, 1 or 2
var random:int = int(Math.random () * sounds[0].length);
// if it's the 1st button so pick the sound from the 1st sounds array
if(e.currentTarget.name == 'button_01'){
play_sound(sounds[0][random]);
} else {
play_sound(sounds[1][random]);
}
}
Hope that can help.

RSS gallery as3

Here is my case - I have 10 movie clips on the view and in every movie clip I need to have a loaded picture that RSS. I've managed to get the first one loaded but I need the other 9 as well. Any ideas?
import com.adobe.xml.syndication.generic.FeedFactory;
import com.adobe.xml.syndication.generic.IFeed;
import com.adobe.xml.syndication.generic.IItem;
import flash.display.MovieClip;
import flash.events.MouseEvent;
var rss:XML;
var rss_url:URLRequest = new URLRequest("http://btvnews.bg/lbin/rss.php?section_id=16105?pic_size=300x158");
var rssLoader:URLLoader = new URLLoader(rss_url);
rssLoader.addEventListener(Event.COMPLETE, rssLoaded);
var rssCount;
var rssCounter = 0;
var l = new Loader();
var loaderContext:LoaderContext;
loaderContext= new LoaderContext();
loaderContext.securityDomain=SecurityDomain.currentDomain;
loaderContext.checkPolicyFile = true;
Security.loadPolicyFile('http://img.bg.sof.cmestatic.com/crossdomain.xml');
function rssLoaded(e:Event):void
{
rss = XML(rssLoader.data);
var curImage = rss.channel.item[0].enclosure. # url;
l.load(new URLRequest(curImage));
l.contentLoaderInfo.addEventListener(Event.COMPLETE,doneIt);
function doneIt(e:Event)
{
var bit:Bitmap = e.target.content;
if (bit != null)
{
bit.smoothing = true;
}
}
placer.addChild(l);
After your rss load as you have loaded one images put a for loop for the item
for(var i=0; i < rss.channel.item.length;i++)
{
var img = rss.channel.item[i].enclosure. # url;
//rest of the code to load the image and adding to stage
}

Flash AS3 copyPixels from BitmapData into jpeg screenshot

I have code to create a live screenshot of the stage in my swf.
After that it saves as a jpeg. All good.
Only, I don't need the whole stage, I only need a cutout:
x,y: 357,341
widt,height: 319,483
My code looks like this..
Where and how do I insert the copypixels function?
(I'm a Flash novice, so go easy on me :-)
function mouseReleaseSave(event:MouseEvent):void {
import com.adobe.images.JPGEncoder;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequestHeader;
import flash.net.URLRequest;
var jpgSource:BitmapData = new BitmapData(this.stage.stageWidth, this.stage.stageHeight);
jpgSource.draw(this.stage);
var jpgEncoder:JPGEncoder = new JPGEncoder(70);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
//set the request's header,method and data
var header:URLRequestHeader = new URLRequestHeader("Content-type","application/octet-stream");
var loader:URLLoader = new URLLoader();
//sends jpg bytes to saveJPG.php script
var myRequest:URLRequest = new URLRequest("saveJPG.php");
myRequest.requestHeaders.push(header);
myRequest.method = URLRequestMethod.POST;
myRequest.data = jpgStream;
loader.load(myRequest);
//fire complete event;
loader.addEventListener(Event.COMPLETE,saved);
function saved(e:Event){
//trace the image file name
trace(loader.data);
}
}
This should help:
var subArea:Rectangle = new Rectangle(0,0, 319,483 );
var newBmp:Bitmap = new BitmapData( 319,483 );
var cutoutBmp:Bitmap = new Bitmap( newBmp, PixelSnapping.ALWAYS, true );
cutoutBmp.bitmapData.draw( jpgSource, new Matrix(1, 0, 0, 1, -357, -341) , null, null, subArea, true );

Flash AS3 FileReference - Select and Upload Multiple Files one at a time

I currently have an swf that allows you to select and display a file and upload it to the server using FileReference. This works great but i need to be able to select and display multiple (up to 25 in some cases) and then upload them all at the end.
I know you can use the FileReferenceList to select multiple files at the same time in the dialog popup but my issue is that the user needs to select one at a time, do stuff to that image, then select another, do stuff and so on... then at the end when they press upload it upload them all onto the server.
Is it possible or is there a way so i can maybe add every new selected file into an array, then at the end it uploads all the files in the array either in one go or loops through each until all objects in the array are complete?
Can anyone help? I'll post the full code for my working single file upload below.
Please, please help, i'm limited with flash and have only been learning for 3-4 months and i've been stuck for over a week now :(
Lauren
as3 Code:
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.utils.ByteArray;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.display.MovieClip;
import fl.controls.ProgressBarMode;
import flash.display.Bitmap;
import flash.display.BitmapData;
progressBar.visible=false;
UploadprogressBar.visible=false;
// Create FileReference.
var imageFile:FileReference;
// Create Loader to hold image content
var image_loader:Loader = new Loader();
var image_content:Sprite = new Sprite();
// Get Extension Function.
var imageExtension;
function getExtension($url:String):String {
var extension:String = $url.substring($url.lastIndexOf(".")+1, $url.length);
return extension;
}
// Random Number Function to create new filename on server.
function randomNum(low:Number=0, high:Number=1):Number {
return Math.floor(Math.random() * (1+high-low)) + low;
}
var myNumber:Number= randomNum(1000,9999);
var myString:String= String(myNumber);
var RandomNumbers = myString;
var imageFilePath = (RandomNumbers);
// Select Button Function.
select_btn.addEventListener(MouseEvent.CLICK, onselect_btnClicked);
function onselect_btnClicked(event:MouseEvent):void {
imageFile=new FileReference();
imageFile.addEventListener(Event.SELECT, onFileSelected);
var imageTypeFilter:FileFilter = new FileFilter("JPG/PNG Files","*.jpeg; *.jpg;*.gif;*.png");
imageFile.browse([imageTypeFilter]);
}
// File Selected Function.
function onFileSelected(event:Event):void {
imageFile.addEventListener(Event.COMPLETE, onFileLoaded);
imageFile.addEventListener(ProgressEvent.PROGRESS, onProgress);
var imageFileName = imageFile.name;
imageExtension = getExtension(imageFileName);
imageFile.load();
progressBar.visible=true;
progressBar.mode=ProgressBarMode.MANUAL;
progressBar.minimum=0;
progressBar.maximum=100;
UploadprogressBar.mode=ProgressBarMode.MANUAL;
UploadprogressBar.minimum=0;
UploadprogressBar.maximum=100;
}
// File Progress Function.
function onProgress(event:ProgressEvent):void {
var percentLoaded:Number=event.bytesLoaded/event.bytesTotal*100;
progressBar.setProgress(percentLoaded, 100);
}
// File Loaded Function.
function onFileLoaded(event:Event):void {
var fileReference:FileReference=event.target as FileReference;
var data:ByteArray=fileReference["data"];
var movieClipLoader:Loader=new Loader();
movieClipLoader.loadBytes(data);
movieClipLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onMovieClipLoaderComplete);
imageFile.removeEventListener(Event.COMPLETE, onFileLoaded);
imageFile.removeEventListener(ProgressEvent.PROGRESS, onProgress);
}
// Load Image onto Stage Function.
function onMovieClipLoaderComplete(event:Event):void {
var loadedContent:DisplayObject=event.target.content;
image_loader =event.target.loader as Loader;
var scaleWidth:Number=345/image_loader.width;
image_loader.scaleX=image_loader.scaleY=scaleWidth;
image_loader.height=200;
image_loader.scaleX=image_loader.scaleY;
image_loader.x=10;
image_loader.y=10;
image_content.buttonMode=true;
image_content.addChild(image_loader);
addChild(image_content);
}
// Upload Button Function.
upload_btn.addEventListener(MouseEvent.CLICK, onupload_btnClicked);
function onupload_btnClicked(event:MouseEvent):void {
var filename:String=imageFile.name;
var urlRequest:URLRequest = new URLRequest("http://www.xxxxx.com/xxxxx/file-reference.php");
var variables:URLVariables = new URLVariables();
urlRequest.method = URLRequestMethod.POST;
imageFile.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
imageFile.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadComplete);
variables.ID = (RandomNumbers);
urlRequest.data = variables;
imageFile.upload(urlRequest);
}
// File Upload Progress Function.
function onUploadProgress(event:ProgressEvent):void {
var percentLoaded:Number=event.bytesLoaded/event.bytesTotal*100;
UploadprogressBar.setProgress(percentLoaded, 100);
trace("loaded: "+percentLoaded+"%");
upload_status_txt.text='upload in progress...';
}
// Upload File Completed Function.
function onUploadComplete(event:Event):void {
upload_status_txt.text='upload complete';
imageFile.removeEventListener(ProgressEvent.PROGRESS, onProgress);
imageFile.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadComplete);
UploadprogressBar.visible=false;
}
php Server Code:
<?php
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$fileID = $_POST['ID'];
$filename = basename( $_FILES['Filedata']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
$uploadID = $fileID.'.'.$extension;
if (move_uploaded_file($_FILES['Filedata']['tmp_name'], "images/".$uploadID))
{
echo "OK";
}
else
{
echo "ERROR";
}
?>
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html
"When you call the FileReferenceList.browse() method, which creates an array of FileReference objects."
You need to use FileReferenceList instead of FileReference.

Full Flex Display Object to Image

I have a requirement for generating a UIComponent displayed into an Image. Am using the PNGEncoder as well as JPEGEncoder to generate the image.
var bd:BitmapData = new BitmapData(uiComp.measuredWidth,uiComp.measuredHeight);
bd.draw(uiComp, new Matrix());
var bitmap:Bitmap = new Bitmap(bd);
bytes = jpgenc.encode(bd);
The code is working perfectly in normaly scenarios. But the problem comes in low resolution screens, if the canvas is having scroll bar, only the displayed contents, i mean omitting the contents belows the scrolled location is coming. Is there any way that I can convert the complete canvas completely into an image, even if it having scroll bar! Please help!
Cheers, PK
I think ImageSnapshot can take a screenshot even if the component is cut off or even if its visible property is set to false.
import mx.core.IUIComponent;
import mx.graphics.ImageSnapshot;
private function takeSnapshot(source:IBitmapDrawable):void {
var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(source);
var imageByteArray:ByteArray = imageSnap.data as ByteArray;
swfLoader.load(imageByteArray);
}
Using Imagesnap with PNGEncoder i was able to get the Screenshot with compression
import flash.filesystem.FileStream;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import mx.graphics.ImageSnapshot;
import mx.graphics.codec.PNGEncoder;
...
...
...
...
ImageSnapshot.defaultEncoder = PNGEncoder;
var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(FlexGlobals.topLevelApplication as IBitmapDrawable);
var stream:FileStream = openStream("screenshot.png");
stream.writeBytes(imageSnap.data);
stream.close();
...
...
...
...
private static function openStream(fileName:String):FileStream
{
var file:File = File.documentsDirectory.resolvePath(fileName);
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
return stream;
}