Alchemy - asynchronous jpeg encoding #2

over 1 year ago malczak alchemy comments

I have recently reopen an old alchemy project - asynchronous jpeg encoding. I have done it mainly because, I wanted (once again) to try to resolve all memory leaks in jpeg encoding library. And I think finally did that, moreover I found a way to even speedup previous asynchronous encoding.
In example below we can create a large BitmapData and then encode it to create jpg image. Encoding can be done using asynchronous or synchronous call to libjpeg.


Synchronous method is defined as :
encode( src:BimapData, image_data:ByteArrat, imageWidth:uint, imageHeight:uint, quality:int );



Parameters:


src:BitmapData - bitmapData to be encoded. cannot be null !

image_data:ByteArray - buffer where jpeg image will be written to. cannot be null !

imageWidth:int - 'src' image width

imageHeight:int - 'src' image height

quality:int - jpeg quality (1-100)


Asynchronous method is defined as :
encodeAsync( callback:Function, src:BimapData, image_data:ByteArrat, imageWidth:uint, imageHeight:uint, quality:int, tuning:int );

Parameters:


callback:Function - callback function to be called when compression is finished. function is invoked with out parameter, image_data byteArray (the same passed as a image_data parameter

src:BitmapData - see synchronous method

image_data:ByteArray - see synchronous method

imageWidth:int - see synchronous method

imageHeight:int - see synchronous method

quality:int - see synchronous method

tuning:int - this is most important parameter, it defines 'how often' method is going to interrupted and control flow returned to other parts of application. it should be interpreted, rather as a 'number of scanlines to be compressed in a single timeslice'


see the example below ...

Flash player (ver. 10.0.0) is required to see this content. Please update to newest possible version.

Get newest Adobe Flash player


for source code (right click on flash above -> view source)



download jpeg encoder library jpegencoder_10092010.swc

Comments

over 1 year ago felix #0

Fantastic! Thanks Mateusz!

over 1 year ago James http://www.psyked.co.uk/ #1

Awesome, thanks! :)

One day I'll master Alchemy stuff...

over 1 year ago Klas Lundberg http://last.instinct.se/ #2

Really great! I've updated my tutorial on how to use it in Flash at http://last.instinct.se/graphics-and-effects/using-the-fast-asynchronous-alchemy-jpeg-encoder-in-flash/640

Keep up the good work!

over 1 year ago Einar Öberg http://www.inear.se #3

Perfect! Just what I needed. I'm doing a jpg-fallback-generator in Air for banner-ads. So thanks!

over 1 year ago Parez #4

Sorry, but what classes do I have to import in my project if working in Flash Professional?

over 1 year ago Tracy #5

I would like to thank you for you code. I have been using code based off your previous one for a while now.

Would you mind sharing your alchemy code like you did for the previous revision? When I try to compile outside of Flash Builder I get the dreaded "unknown opcode?? 60" and I can't update my flex compiler on my project. I also need to make some tweaks to things like cinfo.dct_method, h_samp_factor, etc. and I would love to be able to get your new tweaks in.

over 1 year ago Adrian #6

I get this error when I try to encode multiple images. It does the first 4 images, however, after that I get the error and it just dies. I'm using flex builder 4.

BTW, awesome library! Thanks a lot.

Error #1009: Cannot access a property or method of a null object reference.
at ValueTracker/get()
at CAS3ValTypemap/fromC()
at Function/<anonymous>()
at cmodule.aircall::FSM_compressSingleAsync_/work()
at cmodule.aircall::CRunner/work()
at Function/<anonymous>()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()

over 1 year ago Adrian #7

I got it to work without errors. The solution is to wait for the encoder handler to finish before you can start the next encode. However, the resulting encoded images are coming out with line colors and a lot of noise. Actually that's all I can see from the output. Any ideas?

Thanks!

over 1 year ago Dennis #8

I'm also working on a project in Flex 3.5, and I can't use your SWC in my project. I also get "unknown opcode?? 60" which I'm sure is because of missing opcodes between Flex 3.5 and Flex 4.

Would it be possible to get the Alchemy source, or a SWC compiled for Flex 3.5?

over 1 year ago Jury #9

Does Alchemy keep EXIF information ? We were going to use it for a photo upload purposes, but it broke EXIF info from the photos.

over 1 year ago Kirmani #10

When I do sync "encode" with a file more than 1000 pixels in height and width, the following is shown:
---------------------------------------------------
RangeError: Error #1506: The specified range is invalid.
at cmodule.aircall::FSM_imalloc$/start()
at cmodule.aircall::FSM_pubrealloc/work()
at Function/<anonymous>()
at Function/<anonymous>()
at GraFix_fla::MainTimeline/callSyncEncoder()[GraFix_fla.MainTimeline::frame1:32]
at GraFix_fla::MainTimeline/getFileSizeByDimension()[GraFix_fla.MainTimeline::frame1:985]
at GraFix_fla::MainTimeline/updateEstimatedFileSize()[GraFix_fla.MainTimeline::frame1:961]
at GraFix_fla::MainTimeline/onLoadImage()[GraFix_fla.MainTimeline::frame1:630]

over 1 year ago Bora http://www.javaloper.com #11

Thanx for swc.

My question : private function compressFinished( out:ByteArray ):void......

out is null, what is wrong ?

over 1 year ago birpal #12

i have to create a mask effect for which i have used two sprites object, the parent object is set with "blendmode.layer" as it's property and masked child is set with blendmode.erase(with mask graphics drawn on it). the swf is running well with my mask effect but when i am using alchemy tool to extract images so that i can run my swf as video , the images are coming with erase object(means the extracted image also show the graphics of mask child) which changed the video output...we r using Synchronous method for extraction...please can u help me how can i make my output as original or how can the erase object should not be visible(alpha channel is not supported)....

over 1 year ago akil #13

This is a great library!, thank you for sharing.

over 1 year ago kkm #14

very nice for me, but how can I disable trace ValueTracker extra release!: ..
thank you very much ...

over 1 year ago zak #15

Is this provided under the MIT license?

about 1 year ago Andrey #16

Wondering about the license too. Is it MIT or GPL or something else?

about 1 year ago ancle http://www.flash-gordon.ru/ #17

For russian coders.

Сравнение JPEG кодировщиков по-русски.

http://www.flash-gordon.ru/vs-jpeg-encoders/

about 1 year ago jase21 #18

Please don't make it GPL. Maybe lesser GPL or MPL. Make it available for other works. Don't plague it with GPL v3.
Could you please make the alchemy code (the C code) available? It would be of great help. Atleast we could learn how its done.
Thanks. Awesome library!

about 1 year ago Edw.M #19

Hello,

I tried to use your functions with adobe flash cs5 but when I import your file

I got this error:

Line 20 1172: Definition cmodule.jpegencoder:CLibInit could not be found.

I put your file in the same folder that my fla file, and I check the "export swc" option on publish settings.

Does anyone can help me?

Thanks.

about 1 year ago Alexander #20

Would it be possible to get a swc without the trace statements? Also, would it be possible to get an event for encoding progress?

Besides that, great work :-)

11 months ago zanuka http://zanuka.com #21

great encoder... but how about adding support for transparent .png's ?

10 months ago barry #22

It may be faster than Thibault's, but that's not much use if it doesn't actually produce jpegs. All i get are either completely black images or just a few lines of pixels.

Also it adds over 400kb to my swf and the first parameter for encode isn't actually BitmapData.

But apart form those facts, thanks for sharing...

9 months ago Tim #23

Same here as Barry. All I get is a whole image of black. Any thoughts?

9 months ago focus http://blog.codestage.ru #24

Hi! Thank you for this really fast and kicking-ass encoder.
But Log "ValueTracker extra release!: " + param1 from the ValueTracker class is really annoying)

7 months ago JD #25

Same as Barry and Tim. Black or grey images only....

7 months ago JD #26

Solved my problem... The first parameter is not BitmapData, it's a byteArray!

var _jpgArray:ByteArray = bitmapData.getPixels(bitmapData.rect);
_jpgArray.position = 0;
jpegEncoder.encode(_jpgArray, encoded, bitmapData.width, bitmapData.height, 60);

6 months ago yauidea http://www.yauidea.com #27

the code is updated to be
import cmodule.aircall.CLibInit;

6 months ago David Baron #28

Hi There,

Sorry to be such a newbie here, but I've read the 'prior' article that this replaces and I'm a bit confused. Does this use 'C' routines/files somewhere? I am writing my app in Flex 4, for use on Windows and Macs. Will this be compatible? I also notice that this web page does not actually 'show' the demos that it refers to. It seems to be asking for FlashPlayer 10. I have 10.3.x. Shouldn't they show?

Regardless, and in lieu of the demo (and the accompanying ability to view the source), do I simply download the swc, copy it into my libs package, and boom, I'm good?

Thanks,

-David

5 months ago Kamil #29

I'm getting this error??? usually on loading up a second pic. Working in flashbuilder 4.5.1 any help is appreciated.

RangeError: Error #1506: The specified range is invalid.
at cmodule.aircall::FSM_imalloc$/start()
at cmodule.aircall::FSM_pubrealloc/work()
at cmodule.aircall::CRunner/work()
at Function/<anonymous>()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()

my code is as follows:
private var im:img;
private var jpgStream:ByteArray;
private var jpeglib:Object;
private var jpeginit:CLibInit = new CLibInit(); // get library

public function save_image(_im:img, pg:Number):void
{
var bm:BitmapData = Bitmap(_im.getChildAt(0)).bitmapData;
im = _im;

var imgData:ByteArray = bm.getPixels(bm.rect);
jpgStream = new ByteArray();
imgData.position = 0;

trace(bm == null);
var jpegQuality:Number = 40;

if (!jpeglib) {
jpeglib=jpeginit.init();
}
jpeglib.encodeAsync(encodeComplete, imgData, jpgStream, bm.width, bm.height, jpegQuality);
}

private function encodeComplete(e:Event):void {
trace("Encoding complete");

file = File.documentsDirectory.resolvePath("Pic-A-Note/" + albumName + "/object_layer_" + im.name + ".pn");
fs.open(file, FileMode.WRITE);
fs.writeBytes(jpgStream,0);
fs.close();
}

4 months ago Joonas Mankki #30

I know this stuff is as old as the heaven itself, and I don't know if this project is updated anymore, but is there a source code for this version available somewhere?

4 months ago widomin #31

Hello.
Someone have an example of the implementation in Flex?
I need an async encode example becausw i couldn´t make mine work.

Thanks a lot

Willy

3 months ago Brian #32

Kamil, same issue here "RangeError: Error #1506: The specified range is invalid. " Did you ever find a resolution to the issue?

3 months ago Brian #33

I found a resolution to the Error #1506 problem. Try using this new version of the swc (as3_jpeg_wrapper.swc) found in this post (http://www.websector.de/blog/2009/06/21/speed-up-jpeg-encoding-using-alchemy/), plus initialize the encoder object once in the creationComplete handler.

- Brian

3 months ago Jim #34

Dont forget to reset the bytearray position to 0 before trying to write file ex: jpgStream.position = 0;

3 months ago Ram #35

Not sure why but it points to install FlashPlayer 10, however I have it installed. Also re-installed 10.1.53 version & confirmed but no gain.

Can you please put a direct link to Flex Example? It wold be helpful.

21 days ago Clay35Lilly http://goodfinance-blog.com #36

Some time before, I really needed to buy a house for my corporation but I didn't have enough cash and could not buy anything. Thank heaven my dude adviced to get the <a href="http://goodfinance-blog.com/topics/home-loans">home loans</a> from creditors. Hence, I acted so and was happy with my auto loan.

New comment

  1. (with http or https prefix)

  2. (use [code][/code] tags to post a code snippet)

  3. (javascript is required)

Website content premeditately commited by malczak & sobstel.
Layout by mlando. Icons by dryicons.com. All rights reserved.