Actionscript 3 Load> Combine> and Save External Images - actionscript

I'm new to actionscript 3, So Thank you in advance for any help you can give. Bascially what I'm trying to do is load 2 or more external images, all the same size and resolution, then combine or composite them one on top of the other, then save that result as a new image using a jpeg or png encoder.
I don't want to take a snapshot of the stage, I'd like to save the images with thier original resolution. So far the only thing I've been able to do is load two images, and composite them on the stage. thats about it.
Can someone please give some insight into how to accomplish this. I'm using flash pro CS5.5, and writing code in a class file, not on the timeline. Here is a copy of the code.
package
{
import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.*;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.utils.ByteArray;
public class imageComposite extends MovieClip
{
var images:Array = ["koala.png","koala2.png"];//two images
public function imageComposite()
{
// constructor code
var thumbLoader:Loader;
for (var i:uint = 0; i < images.length; i++)
{
thumbLoader = new Loader;
thumbLoader.load(new URLRequest(("assets/" + images[i])));
addChild(thumbLoader);
}
thumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,bmpData);
}
public function bmpData(evt:Event):void
{
trace("Event was completed successfully!");
}
}
}

First you put both the Loader objects into a separate "holder" object.
// constructor code
var holder:Sprite = new Sprite();
addChild(holder);
var thumbLoader:Loader;
for (var i:uint = 0; i < images.length; i++)
{
thumbLoader = new Loader;
thumbLoader.load(new URLRequest(("assets/" + images[i])));
holder.addChild(thumbLoader);
}
...
Later in your "complete" event handler:
var bitmapData:BitmapData = new BitmapData(holder.width, holder.height, false);
bitmapData.draw(holder);
var byteArray:ByteArray = PNGEncoder.encode(bitmapData);
Then you can write this byteArray object to the server or to disk (desktop AIR application).

Thank you so very much for taking the time to offer your knowledge, it was more then helpful. The code you gave me worked perfectly with one exception. the "holder" variable has to be declared outside of the function. I got alittle bit of an access error, but when I placed it outside the function it worked just fine.
Anyway, i've expanded on the code adding the ability to save. I just put a movieClip on the the stage with instance name of "saveButt_mc". Then added the ability to save using fileReference. My goal is to have it autosave to a server using php, but for now this will have to do.
Heres my final code, thanks again for the help.
-D
package
{
import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.*;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.utils.ByteArray;
import flash.display.Sprite;
import flash.net.FileReference;
import flash.net.FileFilter;
import com.adobe.images.PNGEncoder;
public class imageComposite extends MovieClip
{
var images:Array = ["koala.png","koala2.png"];//two images
var holder:Sprite = new Sprite();
public function imageComposite()
{
// constructor code
addChild(holder);
var thumbLoader:Loader;
for (var i:uint = 0; i < images.length; i++)
{
thumbLoader = new Loader ;
thumbLoader.load(new URLRequest(("assets/" + images[i])));
holder.addChild(thumbLoader);
}
//thumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, bmpData);
saveButt_mc.addEventListener(MouseEvent.CLICK, bmpData);
addChild(saveButt_mc);
saveButt_mc.buttonMode = true;
}
//need contentLoaderInfo to access loader data;
public function bmpData(evt:Event):void
{
var bitmapData:BitmapData = new BitmapData(holder.width,holder.height,false);
bitmapData.draw(holder);
var byteArray:ByteArray = PNGEncoder.encode(bitmapData);
var file:FileReference = new FileReference();
file.save(byteArray, "newImage.jpg");
trace("Event was completed successfully!");
}
}
}

Related

Initialising Apache Jena TDB Dataset

I am using Apache Jena from within Tomcat 8 under Windows 10 (Eclipse IDE) and am not able to initialise the TDB Dataset. The initialisation code is put in the static initialiser inside a try-catch block but no exception is being thrown and the finally clause is getting invoked. I tried with relative directory names, absolute path names, as well as empty path (in memory dataset). The
dataset remains null and so triples cannot be written. What do I need to change in the code
to initialise the dataset?
Here is the code:
package knowledgegraph;
import org.apache.jena.tdb.TDBFactory;
import org.apache.jena.rdf.model.*;
import org.apache.jena.shared.JenaException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import org.apache.jena.query.Dataset;
import org.apache.jena.query.ReadWrite;
public class JenaProcessor {
static Dataset dataset = null;
static String ns = "http://www.lke.com/lke.owl#";
static {
try {
// dataset = TDBFactory.createDataset("lke");
// dataset = TDBFactory.createDataset("C:\\Users\\Diptendu\\Desktop\\lke");
dataset = TDBFactory.createDataset();
System.out.println("TDB initialised");
}
// catch(Exception ex) {
catch(JenaException ex) {
ex.printStackTrace();
}
finally {
System.out.println("Finally clause");
}
}
static public void writeTriple(String corpus_file_id, String subject, String predicate, String object) {
dataset.begin(ReadWrite.WRITE) ;
Model model = null;
try {
model = dataset.getNamedModel(corpus_file_id);
// model.enterCriticalSection(Lock.WRITE);
// write triples to model
Resource subjectResource = model.createResource(ns.concat(subject));
Property property = model.createProperty(ns.concat(predicate));
Resource objectResource = model.createResource(ns.concat(object));
// model.add(subjectResource, property, objectResource);
Statement statement = model.createStatement(subjectResource, property, objectResource);
model.add(statement);
dataset.commit();
// TDB.sync(model);
} finally {
// model.leaveCriticalSection();
model.close();
dataset.end();
}
}
}
sked and responded to on users#jena:
https://lists.apache.org/thread.html/r9f788bf21ceb3991329ab0ba3c649d94f2983f92aa3c0a76af788e52%40%3Cusers.jena.apache.org%3E
It's because you are trying to close the model after you've committed
the transaction so the error message is quite correct in that you are
no longer in a transaction at that point
Put the dataset.commit() after the model.close() line and it will work
Rob

mystery Error #1063: Argument count mismatch

So I'm getting a "Error #1063: Argument count mismatch" error. The weird thing is that it isn't keeping the game from running, but I would like to know why I'm even getting an error in the first place. The full error is:
ArgumentError: Error #1063: Argument count mismatch on Hock(). Expected 3, got 0.
at flash.display::Sprite/constructChildren()
at flash.display::Sprite()
at flash.display::MovieClip()
at PlayScreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\PlayScreen.as:30]
at Main/addPlayscreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\Main.as:17]
at Main()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\Main.as:13]
at runtime::ContentPlayer/loadInitialContent()
at runtime::ContentPlayer/playRawContent()
at runtime::ContentPlayer/playContent()
at runtime::AppRunner/run()
at ADLAppEntry/run()
at global/runtime::ADLEntry()
The Code for PlayScreen is:
import flashx.textLayout.formats.BackgroundColor;
import flash.display.SimpleButton;
import flash.ui.Mouse;
import flash.text.TextField;
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class PlayScreen extends MovieClip
{
public var batArmy:Array;
public var hockArmy:Array;
public var shadow:Shadow;
public var crossHairs:CrossHairs;
var Layer01:MovieClip;
var Layer02:MovieClip;
var Layer03:MovieClip;
var Layer04:MovieClip;
var Layer05:MovieClip;
var randomX:Number = 300 + (660 - 300) * Math.random();
public function PlayScreen()
{
//Mouse.hide();
addBatButton.addEventListener(MouseEvent.CLICK, addBat);
addHockButton.addEventListener(MouseEvent.CLICK, addHock);
batArmy = new Array();
hockArmy = new Array();
//addEventListener(Event.ENTER_FRAME, crossHairsMove);
//stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
Layer01 = new MovieClip;
this.addChild(Layer01);
Layer02 = new MovieClip;
this.addChild(Layer02);
Layer03 = new MovieClip;
this.addChild(Layer03);
Layer04 = new MovieClip;
this.addChild(Layer04);
Layer05 = new MovieClip;
this.addChild(Layer05);
//add crossHair
/*crossHairs = new CrossHairs(mouseX,mouseY,this);
Layer05.addChild (crossHairs);
addEventListener(Event.ENTER_FRAME, crossHairsMove);*/
}
/*public function onKeyPress( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.DOWN )
{
trace("yar");
addBat;
}
}*/
public function addBat( mouseEvent:MouseEvent ):void
{
var randomX:Number = 300 + (660 - 300) * Math.random();
var newBat = new Bat( randomX, -50, this);
batArmy.push ( newBat );
Layer02.addChild (newBat);
}
public function addHock( mouseEvent:MouseEvent ):void
{
var newHock = new Hock(-72, 170, this);
hockArmy.push ( newHock );
Layer02.addChild (newHock);
}
/*public function crossHairsMove ( e:Event ):void
{
crossHairs.x = mouseX;
crossHairs.y = mouseY;
}*/
}
and from the looks of it the error has something to do with the Hock class, so here's the code for that:
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.ui.Mouse;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class Hock extends MovieClip
{
private var _screen: PlayScreen;
public var xSpeed:Number;
public function Hock( startX:Number, startY:Number, screen:PlayScreen )
{
_screen = screen;
x = startX;
y = startY;
width = 100;
scaleY = scaleX;
addEventListener(Event.ENTER_FRAME, moveRightFar);
addEventListener(Event.ENTER_FRAME, moveSpeed)
}
public function moveSpeed( e:Event ):void
{
x += xSpeed;
}
public function moveRightFar ( e:Event): void
{
if (x < 0)
{
gotoAndStop("rollRight");
xSpeed = 13;
}
else if (x >= 240)
{
gotoAndStop("still")
xSpeed = 0;
}
}
}
Now I could be wrong but I think it's having a problem with var newHock = new Hock(-72, 170, this); in the "addHock" function, but I have 3 arguments there, not 0. Right? Anyway, like I said, it's not keeping the game from running but it is kind of annoying, so any insight is welcome. I'm sure it's something obvious. Thanks!
I have a guess, but I'll explain how i got there first ...
the first line of the stacktrace pointing at your source code is
at PlayScreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\PlayScreen.as:30]
which points at the first line of the constructor of PlayScreen: addBatButton.addEventListener(MouseEvent.CLICK, addBat);
but obviously the problem is not there ...
But PlayScreen extends MovieClip and since you didn't specifically included a super() statement, the compiler will put that at as the first command. In fact, the previous lines of the stack point to the constructor of MovieClip and then to a mysterious constructChildren() method of Sprite
That happens to be an internal method used to create the childs of the Sprite that you might have setup on your clip's stage directly from Animate.
So my guess is, the player is trying to instantiate a symbol that extends Hock and that you positioned on the stage somewhere, and of course is doing it by passing zero arguments because that's what a normal Sprite would expect.
Check your library to see what extends Hock and then see which one of those is placed in some other symbol's stage. Your options then will be to remove that and create it from code or to rework the class signature to take zero arguments.

AlivePdf create a map chart

I'm building a pure actionscript project and would like to create a pdf with an map chart of the world to display my data.
It's possible to create a map and save as image and then embed in pdf with alivepdf?
package
{
import MyButton;
import flash.display.*;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.external.*;
import flash.net.*;
import flash.net.FileReference;
import flash.system.Security;
import flash.utils.ByteArray;
import org.alivepdf.display.*;
import org.alivepdf.fonts.*;
import org.alivepdf.layout.*;
import org.alivepdf.pdf.*;
import org.alivepdf.saving.*;
public class WorldTest extends Sprite
{
private var saveButton:MyButton = new MyButton();
// declared of logo or imagen on top of the PDF's document.
[Embed(source="FCMap_World.swf", mimeType="application/octet-stream" )]
protected var jpgBytes:Class;
protected var pdf:PDF;
public function WorldTest() {
saveButton.y = 0;
addChild(saveButton);
this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
}
protected function onMouseClickEvent(event:Event):void{
pdf = new PDF(Orientation.LANDSCAPE, Unit.MM, Size.LETTER);
pdf.setDisplayMode(Display.FULL_WIDTH);
pdf.addPage();
pdf.addImage(new jpgBytes() as DisplayObject, null, 0, 0, 0);
var bytes:ByteArray = pdf.save(Method.LOCAL);
var file:FileReference = new FileReference();
file.save(bytes, "myPDF.pdf");
}
}
}
It seems like you are trying to add swf file as image.
You need to make an image from it first.
var map : MovieClip = new jpgBytes();
var bitmapData : BitmapData = new BitmapData(map.width, map.height);
bitmapData.draw(map);
var bitmap : Bitmap = new Bitmap(bitmapData);
You can try to use another library called PDFcase for creating pdf in ActionScript.
This example shows how to add images to pdf.

iOS deve with Starling framework: take a screenshot and save it to the camera roll

I use flash for ios development and I use starling framework.
I'm trying to take a screenshot and then save it to the camera roll, but cameraRoll only accepts bitmapdata. How am I going to convert sprite to bitmapdata? Thanks a million!!
You can convert Sprite to BitmapData using BitmapData.draw() method.
Here's an example.
Try to get an byte array for this use can use Encoder like JPGEncoder or PNGEncoder from byte array you can easily convert to bitmapData.
And the code which i used for converting byte array to bitmapData is here. I hope it would be helpfull for you.If you send any byteArray by calling this class it would convert you bitmapData and return back using callBack Function.
package browsingImages
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.ByteArray;
import scenes.Subscenes.KeepDiary;
public class BitmapDataConverter
{
// private var _KeepDiary:KeepDiary;
private var bmpData:BitmapData;
private var _loader:Loader;
private var _callB:Function;
public function BitmapDataConverter(byteArr:ByteArray,callB:Function)
{
_callB=callB;
getBitmapFunc(byteArr);
}
private function getBitmapFunc(bytArr:ByteArray):void{
if(bytArr != null){
bmpData = new BitmapData(100, 100, true,0xFFFFFF);
_loader = new Loader();
_loader.loadBytes(bytArr);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderAdded);
}
}
private function onLoaderAdded(eve:Event):void{
_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoaderAdded);
bmpData.draw(_loader);
bmpData = Bitmap(_loader.content).bitmapData;
if(_callB != null)
_callB(bmpData);
}
}
}
Actually, you cant use draw for starling's Sprite.
this code works for me:
public static function copyAsBitmapData(displayObject:DisplayObject, transparentBackground:Boolean = true, backgroundColor:uint = 0xcccccc):BitmapData
{
if (displayObject == null || isNaN(displayObject.width)|| isNaN(displayObject.height))
return null;
var resultRect:Rectangle = new Rectangle();
displayObject.getBounds(displayObject, resultRect);
var result:BitmapData = new BitmapData(displayObject.width, displayObject.height, transparentBackground, backgroundColor);
var context:Context3D = Starling.context;
var support:RenderSupport = new RenderSupport();
RenderSupport.clear();
support.setOrthographicProjection(0, 0, Starling.current.stage.stageWidth, Starling.current.stage.stageHeight);
support.applyBlendMode(true);
support.translateMatrix( -resultRect.x, -resultRect.y);
support.pushMatrix();
support.blendMode = displayObject.blendMode;
displayObject.render(support, 1.0);
support.popMatrix();
support.finishQuadBatch();
context.drawToBitmapData(result);
return result;
}

Actionscript 3.0 - Trying to remove a child

Simple simple problem but I can't get it to work.
So I just have a class with a display object, a ball. I create instances of it from Main.as
and run a for loop to check if I hit the ball and if I do, I want to remove the object.
But I can't.
What's wrong with my code?
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Main extends Sprite
{
private var clay:Clay;
private var clayCollection:Vector.<Clay> = new Vector.<Clay>;
private var crash:Crash;
private var crashCollection:Vector.<Crash> = new Vector.<Crash>;
private var timer:Timer = new Timer(0);
private var newClayTimer:Timer = new Timer(1000);
public function Main()
{
newClayTimer.start();
newClayTimer.addEventListener(TimerEvent.TIMER, addNewClay);
stage.addEventListener(MouseEvent.CLICK, checkForHit);
}
private function checkForHit(e:MouseEvent):void
{
if (clayCollection.length > 0)
{
for (var i:int = 0; i < clayCollection.length; i++)
{
if (e.target.hitTestObject(clayCollection[i]))
{
clayCollection.splice(i, 1);
removeChild(clayCollection[i]);
}
}
}
}
private function addNewClay(e:TimerEvent):void
{
clay = new Clay();
addChild(clay);
clayCollection.push(clay);
}
}
}
Try something like this
for (var i:int = 0; i < clayCollection.length; i++) {
var clay:Clay = clayCollection[i];
if (e.target.hitTextObject) {
//seems to me all clays will hit test as true with the stage?
removeChild(clay);
clayCollection.splice(i, 1);
}
}
That way you know that the object that you're trying to remove is definitely the one that hit tested true.
I agree with Amy, listen for a click on the instance of clay, not the stage. You can still remove it from your array, something like this (untested code):
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Main extends Sprite
{
private var clay:Clay;
private var clayCollection:Vector.<Clay> = new Vector.<Clay>;
private var crash:Crash;
private var crashCollection:Vector.<Crash> = new Vector.<Crash>;
private var timer:Timer = new Timer(0);
private var newClayTimer:Timer = new Timer(1000);
public function Main()
{
newClayTimer.start();
newClayTimer.addEventListener(TimerEvent.TIMER, addNewClay);
}
private function checkForHit(e:MouseEvent):void
{
// identify the target as Clay
var clay:Clay = e.target as Clay;
if(contains(clay)) removeChild(clay);
// remove it from your array
for each (var c:Clay in clayCollection) {
if (c == clay) clayCollection.splice(clayCollection.indexOf(c), 1);
}
}
private function addNewClay(e:TimerEvent):void
{
clay = new Clay();
clay.addEventListener(MouseEvent.CLICK, checkForHit);
addChild(clay);
clayCollection.push(clay);
}
}
}
When the program created a instance of the object and you mouse click it, the debugger threw this error.
Main Thread (Suspended: RangeError: Error #1125: The index 0 is out of range 0.)
Main/checkForHit
The fix is that you need to delimit the index of the loop as you slice it. Also the sequence of when you apply the splice and delimit is important.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Main extends Sprite {
private var clay:Clay;
private var clayCollection:Vector.<Clay> = new Vector.<Clay>;
private var timer:Timer = new Timer(0);
private var newClayTimer:Timer = new Timer(1000);
public function Main(){
newClayTimer.start();
newClayTimer.addEventListener(TimerEvent.TIMER, addNewClay);
stage.addEventListener(MouseEvent.CLICK, checkForHit);
}//END MAIN()
private function checkForHit(e:MouseEvent):void{
if (clayCollection.length > 0)
{
for (var i:int = 0; i != clayCollection.length; i++)
{
trace(i,clayCollection.length);
if (e.target.hitTestObject(clayCollection[i]))
{
removeChild(clayCollection[i]);
clayCollection.splice(i, 1);
i--;
}
}
}
}//END checkForHit()
private function addNewClay(e:TimerEvent):void{
clay = new Clay();
addChild(clay);
clayCollection.push(clay);
}//END addNewClay()
}//END MAINCLASS
}//END PACKAGE

Resources