For personal needs, for the Xamarin.Forms.Map control, I need to create a CustomPin extension. UWP part (PCL project)
I create a MapIcon like it:
nativeMap.MapElements.Add(new MapIcon()
{
Title = pin.Name,
Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Pin/customicon.png")),
Location = new Geopoint(new BasicGeoposition() { Latitude = pin.Position.Latitude, Longitude = pin.Position.Longitude }),
NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0)
});
However, by this way, I can't set the Image's size.
I then want to use an Image from my PCL part, resize it and convert it into a IRandomAccessStreamReference. To realize it, I need to convert my Image into a stream, but I can't find the way to make it works ><
Example of the function needed:
private IRandomAccessStreamReference ImageToIRandomAccessStreamReference(Image image)
{
//Here I can set the size of my Image
//I convert it into a stream
IRandomAccessStreamReference irasr = RandomAccessStreamReference.CreateFromStream(/* img? */);
//irasr is then created from img
//I return the IRandomAccessStreamReference needed by the MapIcon element
return irasr;
}
Note: The Image paramter img is a Xamarin.Forms.Image
So first, is it possible? If yes, then thank for any help which could help me.. I already search about how to resize the MapIcon and it's not possible directly from the class [MapIcon].(https://msdn.microsoft.com/library/windows/apps/windows.ui.xaml.controls.maps.mapicon.aspx)
Thank for help !
You are right. We can't resize the MapIcon directly as it doesn't provide such properties or methods. MapIcon's size is mostly controlled by the size of image which is set by MapIcon.Image property. And we can set this image's size without using Xamarin.Forms.Image.
To set this image's size, we can take advantage of BitmapDecoder class, BitmapEncoder class and BitmapTransform class like following:
private async System.Threading.Tasks.Task<RandomAccessStreamReference> ResizeImage(StorageFile imageFile, uint scaledWidth, uint scaledHeight)
{
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
{
var decoder = await BitmapDecoder.CreateAsync(fileStream);
//create a RandomAccessStream as output stream
var memStream = new InMemoryRandomAccessStream();
//creates a new BitmapEncoder and initializes it using data from an existing BitmapDecoder
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);
//resize the image
encoder.BitmapTransform.ScaledWidth = scaledWidth;
encoder.BitmapTransform.ScaledHeight = scaledHeight;
//commits and flushes all of the image data
await encoder.FlushAsync();
//return the output stream as RandomAccessStreamReference
return RandomAccessStreamReference.CreateFromStream(memStream);
}
}
And then we can use this method to create a resized image stream reference first and then set it as MapIcon's Image like:
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Pin/customicon.png"));
var imageReference = await ResizeImage(file, 64, 64);
nativeMap.MapElements.Add(new MapIcon()
{
Title = pin.Name,
Image = imageReference,
Location = new Geopoint(new BasicGeoposition() { Latitude = pin.Position.Latitude, Longitude = pin.Position.Longitude }),
NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0)
});
Related
My target is to generate image with A5 format and place some text on it. At the beggining i was trying to accomplish that using System.Drawing.Imaging but seems like Xamarin is not able to work with this. Then I found out SkiaSharp library which seems like would be valid to do this job but i am a bit lost here. How can i correctly generate an image, put some text on it and send via Stream. Note that if there is more text that couldn't fit on single A5 next image should be created.
This is what i got so far:
private void CreateBitmapFromText(List<string> texts)
{
using var surface = SKSurface.Create(width: 640, height: 480, SKColorType.Gray8, SKAlphaType.Premul);
SKCanvas myCanvas = surface.Canvas;
// clear the canvas / fill with white
myCanvas.DrawColor(SKColors.White);
// set up drawing tools
using (var paint = new SKPaint())
{
paint.TextSize = 64.0f;
paint.IsAntialias = true;
paint.Color = new SKColor(0x42, 0x81, 0xA4);
paint.IsStroke = false;
// draw the text
foreach (var text in texts)
{
myCanvas.DrawText(text, ??, ??, paint);
}
}
}
EDIT: with help of #Jason i did this:
var aaa = ToStream(CreateBitmapFromText(new List<string>() {"asas", "vvvv"}), SKEncodedImageFormat.Png);
_printService.PrintImage(aaa);
public Stream ToStream(SKImage image, SKEncodedImageFormat format)
{
SKData encoded = image.Encode(format, 90);
return encoded.AsStream();
}
public SKImage CreateBitmapFromText(List<string> texts)
{
using var surface = SKSurface.Create(width: 640, height: 480, SKColorType.Gray8, SKAlphaType.Premul);
SKCanvas myCanvas = surface.Canvas;
// clear the canvas / fill with white
myCanvas.DrawColor(SKColors.White);
// set up drawing tools
using (var paint = new SKPaint())
{
paint.TextSize = 64.0f;
paint.IsAntialias = true;
paint.Color = new SKColor(0x42, 0x81, 0xA4);
paint.IsStroke = false;
// draw the text
foreach (var text in texts)
{
myCanvas.DrawText(text, 0.0f, 0.0f, paint);
}
}
return surface.Snapshot();
}
When i send it to printer i see this (white paper with some little black chars ?? at the top?)
I was able to easily modify the Xamarin FramedText sample to save a bitmap by adding this to the end of OnCanvasViewPaintSurface
// get the SKImage from SKSurface
var image = surface.Snapshot();
// Encode as PNG, returns SKData
var data = image.Encode(SKEncodedImageFormat.Png, 100);
string path = Path.GetTempFileName();
// write byte[] to file, verify data with image viewer
File.WriteAllBytes(path, data.ToArray());
you should be able to easily modify this to return a byte[] or stream
I want to send photo selected by user in my app to Firebase Storage. I have a simple class with property _imageFile which is set like this:
File _imageFile;
_getImage() async {
var fileName = await ImagePicker.pickImage();
setState(() {
_imageFile = fileName;
});
}
after that I send photo like with this code:
final String rand1 = "${new Random().nextInt(10000)}";
final String rand2 = "${new Random().nextInt(10000)}";
final String rand3 = "${new Random().nextInt(10000)}";
final StorageReference ref = FirebaseStorage.instance.ref().child('${rand1}_${rand2}_${rand3}.jpg');
final StorageUploadTask uploadTask = ref.put(_imageFile);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
print(downloadUrl);
The problem is that the photos are often very large. Is there any method in Flutter/Dart to compress and resize photo before upload? I am ok with loss of quality.
June 05, 2020 - Update
The image_picker plugin now supports an imageQuality paramater. You can do something like
ImagePicker imagePicker = ImagePicker();
PickedFile compressedImage = await imagePicker.getImage(
source: ImageSource.camera,
imageQuality: 85,
);
Old Answer
or if you want to compress an image without using ImagePicker
I ran into this and was able to accomplish compression / resizing with the Dart image package along with path provider. You can look at dart image api and examples for other ways and more help.
Here's what I did:
import 'package:image/image.dart' as Im;
import 'package:path_provider/path_provider.dart';
import 'dart:math' as Math;
void compressImage() async {
File imageFile = await ImagePicker.pickImage();
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
int rand = new Math.Random().nextInt(10000);
Im.Image image = Im.decodeImage(imageFile.readAsBytesSync());
Im.Image smallerImage = Im.copyResize(image, 500); // choose the size here, it will maintain aspect ratio
var compressedImage = new File('$path/img_$rand.jpg')..writeAsBytesSync(Im.encodeJpg(image, quality: 85));
}
Then I uploaded compressedImage to firebase storage. You can adjust the quality that the jpg is saved with using the quality property, in my case I chose 85 (out of 100).
Hope this helps! Let me know if you have any questions.
The image_picker plugin is currently very simple. It would be straightforward to add an option for specifying the desired size/quality of the picked image. If you do this, please send us a pull request!
Use image_picker plugin and call pick image function as
Future<File> imageFile = ImagePicker.pickImage(source: ImageSource.gallery , maxHeight: 200 , maxWidth: 200 );
change maxHeight and maxWidth to whatever size of image you need.
There are many solutions :
Use image_picker package:
You can use the built-in imageQuality property of ImagePicker to compress the image. This property takes a value between 0 and 100 and represents a percentage of the quality of the original image.
First, add image_picker as a dependency in your pubspec.yaml file.
Usage
File _image;
Future getImage() async {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 25,
);
setState(() {
_image = image;
});
}
The advantage of this approach is that it is embedded in the
image_picker package and is therefore incredibly easy to use.
You can also adjust the quality from the Image widget.
Use filterQuality to set the FilterQuality of the image.
Example :
Image.asset('assets/kab1.png', filterQuality: FilterQuality.high,),
These properties are present in AssetImage , NetworkImage , FileImage and MemoryImage.
You can also simply resize the image (Resizing an image can compress it). To do so, try the ResizeImage widget
Another solution is to use flutter_image_compress package
Besides mentioning this native library:
https://pub.dartlang.org/packages/flutter_image_compress
This is a fully dart based compressor with isolates, which might make the compression parallel to UI thread in multi core CPUs.
You might want to use compute function which makes using isolates simpler:
https://docs.flutter.io/flutter/foundation/compute.html
https://flutter.io/cookbook/networking/background-parsing/
import 'package:image/image.dart' as ImageLib;
import 'package:path_provider/path_provider.dart';
Future<void> getCompressedImage(SendPort sendPort) async {
ReceivePort receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
List msg = (await receivePort.first) as List;
String srcPath = msg[0];
String name = msg[1];
String destDirPath = msg[2];
SendPort replyPort = msg[3];
ImageLib.Image image =
ImageLib.decodeImage(await new File(srcPath).readAsBytes());
if (image.width > 500 || image.height > 500) {
image = ImageLib.copyResize(image, 500);
}
File destFile = new File(destDirPath + '/' + name);
await destFile.writeAsBytes(ImageLib.encodeJpg(image, quality: 60));
replyPort.send(destFile.path);
}
Future<File> compressImage(File f) async {
ReceivePort receivePort = ReceivePort();
await Isolate.spawn(getCompressedImage, receivePort.sendPort);
SendPort sendPort = await receivePort.first;
ReceivePort receivePort2 = ReceivePort();
sendPort.send([
f.path,
f.uri.pathSegments.last,
(await getTemporaryDirectory()).path,
receivePort2.sendPort,
]);
var msg = await receivePort2.first;
return new File(msg);
}
if (false ==
await SimplePermissions.checkPermission(
Permission.ReadExternalStorage)) {
await SimplePermissions.requestPermission(
Permission.ReadExternalStorage);
}
File img = await ImagePicker.pickImage(
source: ImageSource.gallery);
if (null != img) {
img = await compressImage(img);
}
The following code is what I use to take an image with the camera and then compress it:
import 'dart:async' show Future;
import 'dart:io' show File;
import 'package:flutter/foundation.dart' show compute;
import 'package:flutter/material.dart' show BuildContext;
import 'package:image/image.dart' as Im;
import 'dart:math' as Math;
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart' show getTemporaryDirectory;
Future<File> takeCompressedPicture(BuildContext context) async {
var _imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
if (_imageFile == null) {
return null;
}
// You can have a loading dialog here but don't forget to pop before return file;
final tempDir = await getTemporaryDirectory();
final rand = Math.Random().nextInt(10000);
_CompressObject compressObject =
_CompressObject(_imageFile, tempDir.path, rand);
String filePath = await _compressImage(compressObject);
print('new path: ' + filePath);
File file = File(filePath);
// Pop loading
return file;
}
Future<String> _compressImage(_CompressObject object) async {
return compute(_decodeImage, object);
}
String _decodeImage(_CompressObject object) {
Im.Image image = Im.decodeImage(object.imageFile.readAsBytesSync());
Im.Image smallerImage = Im.copyResize(
image, 1024); // choose the size here, it will maintain aspect ratio
var decodedImageFile = File(object.path + '/img_${object.rand}.jpg');
decodedImageFile.writeAsBytesSync(Im.encodeJpg(smallerImage, quality: 85));
return decodedImageFile.path;
}
class _CompressObject {
File imageFile;
String path;
int rand;
_CompressObject(this.imageFile, this.path, this.rand);
}
You can call this very easy with this:
import 'path/to/compress_image.dart' as CompressImage;
// ...
File file = await CompressImage.takeCompressedPicture(context);
While i am using
package:image/image.dart
facing below issues
showing blank page while converting image ( may be taking so much process while compressing image)
After compression image was stretched and not looking good
Then used below plugin, same working fine without any issue, even faster and what i expected
https://github.com/btastic/flutter_native_image.git
steps and method available in above link.
You can use a plugin called flutter_image_compress
// Active image file
File _imageFile;
// Select an image via gallery or camera
Future<void> _pickImage(ImageSource source) async {
File selected = await ImagePicker.pickImage(source: source);
// Compress plugin
File compressedImage = await FlutterImageCompress.compressAndGetFile(
selected.path,
selected.path,
quality: 50,
);
setState(() {
_imageFile = compressedImage;
print('compressedimagesize: ${_imageFile.lengthSync()}');
});
}
Voila! Compressed file image
Since you are using Firebase, one option would be using the Extension - Resize Image. It gives you the option to keep or delete the original image and it is very easy to install and use.
You can do as follows,
//Compressing Image
File compressedImg = await FlutterNativeImage.compressImage(
_image.path,
quality: 70,
);
//Compressing Image
Well
1. If you are in mobile you could use flutter_image_compress: ^1.0.0 will do the work
Eg.
Pass youe Uint8List and quality, you will get compressed image in no time.
Future<Uint8List> testComporessList(Uint8List uint8List) async {
var result = await FlutterImageCompress.compressWithList(
uint8List,
quality: 50,
);
return result;
}
2. But If you are in flutter web then you won't get any other option than image picker etc etc.
I end up using javascript. You can find answer here.
Flutter Web: How Do You Compress an Image/File?
Update 2020 'pickImage' is deprecated and shouldn't be used. Use imagePicker.getImage() method instead**
ImagePicker picker = ImagePicker();
PickedFile compressedImage = await imagePicker.getImage(
source: ImageSource.camera,
imageQuality: 80,
);
Doc for ImageQuality :
Returns a PickedFile object wrapping the image that was picked. The
returned PickedFile is intended to be used within a single APP
session. Do not save the file path and use it across sessions. The
source argument controls where the image comes from. This can be
either ImageSource.camera or ImageSource.gallery. Where iOS supports
HEIC images, Android 8 and below doesn't. Android 9 and above only
support HEIC images if used in addition to a size modification, of
which the usage is explained below. If specified, the image will be at
most maxWidth wide and maxHeight tall. Otherwise the image will be
returned at it's original width and height. The imageQuality argument
modifies the quality of the image, ranging from 0-100 where 100 is the
original/max quality. If imageQuality is null, the image with the
original quality will be returned. Compression is only supported for
certain image types such as JPEG and on Android PNG and WebP, too. If
compression is not supported for the image that is picked, a warning
message will be logged. Use preferredCameraDevice to specify the
camera to use when the source is ImageSource.camera. The
preferredCameraDevice is ignored when source is ImageSource.gallery.
It is also ignored if the chosen camera is not supported on the
device. Defaults to CameraDevice.rear. Note that Android has no
documented parameter for an intent to specify if the front or rear
camera should be opened, this function is not guaranteed to work on an
Android device. In Android, the MainActivity can be destroyed for
various reasons. If that happens, the result will be lost in this
call. You can then call getLostData when your app relaunches to
retrieve the lost data.
Current project:
ASP.NET 4.5.2
MVC 5
I am trying to leverage the TinyPNG API, and if I just pipe the image over to it, it works great. However, since the majority of users will be on a mobile device, and these produce images at a far higher resolution than what is needed, I am hoping to reduce the resolution of these files prior to them being piped over to TinyPNG. It is my hope that these resized images will be considerably smaller than the originals, allowing me to conduct a faster round trip.
My code:
public static async Task<byte[]> TinyPng(Stream input, int aspect) {
using(Stream output = new MemoryStream())
using(var png = new TinyPngClient("kxR5d49mYik37CISWkJlC6YQjFMcUZI0")) {
ResizeImage(input, output, aspect, aspect); // Problem area
var result = await png.Compress(output);
using(var reader = new BinaryReader(await (await png.Download(result)).GetImageStreamData())) {
return reader.ReadBytes(result.Output.Size);
}
}
}
public static void ResizeImage(Stream input, Stream output, int newWidth, int maxHeight) {
using(var srcImage = Image.FromStream(input)) {
var newHeight = srcImage.Height * newWidth / srcImage.Width;
if(newHeight > maxHeight) {
newWidth = srcImage.Width * maxHeight / srcImage.Height;
newHeight = maxHeight;
}
using(var newImage = new Bitmap(newWidth, newHeight))
using(var gr = Graphics.FromImage(newImage)) {
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
newImage.Save(output, ImageFormat.Jpeg);
}
}
}
So the ResizeArea is supposed to accept a stream and output a stream, meaning that the TinyPNG .Compress() should work just as well with the output as it would with the original input. Unfortunately, only the .Compress(input) works -- with .Compress(output) TinyPNG throws back an error:
400 - Bad Request. InputMissing, File is empty
I know TinyPNG has its own resizing routines, but I want to do this before the image is sent out over the wire to TinyPNG so that file size (and therefore transmission time) is reduced as much as possible prior to the actual TinyPNG compression.
…Aaaaand I just solved my problem by using another tool entirely.
I found ImageProcessor. Documentation is a royal b**ch to get at because it only comes in a Windows *.chm help file (it’s not online… cue one epic Whisky. Tango. Foxtrot.), but after looking at a few examples it did solve my issue quite nicely:
public static async Task<byte[]> TinyPng(Stream input, int aspect) {
using(var output = new MemoryStream())
using(var png = new TinyPngClient("kxR5d49mYik37CISWkJlC6YQjFMcUZI0")) {
using(var imageFactory = new ImageFactory()) {
imageFactory.Load(input).Resize(new Size(aspect, 0)).Save(output);
}
var result = await png.Compress(output);
using(var reader = new BinaryReader(await (await png.Download(result)).GetImageStreamData())) {
return reader.ReadBytes(result.Output.Size);
}
}
}
and everything is working fine now. Uploads are much faster now as I am not piping a full-sized image straight through to TinyPNG, and since I am storing both final-“full”-sized images as well as thumbnails straight into the database, I am now not piping the whole bloody image twice.
Posted so that other wheel-reinventing chuckleheads like me will actually have something to go on.
The setup
Consider the given scratch program that uses SharpDX, a managed wrapper for Direct* libraries, to render a bitmap and save it as a PNG:
namespace ConsoleApplication5
{
using System;
using System.Diagnostics;
using System.IO;
using SharpDX;
using SharpDX.Direct2D1;
using SharpDX.DirectWrite;
using SharpDX.DXGI;
using SharpDX.IO;
using SharpDX.WIC;
using AlphaMode = SharpDX.Direct2D1.AlphaMode;
using Bitmap = SharpDX.WIC.Bitmap;
using D2DPixelFormat = SharpDX.Direct2D1.PixelFormat;
using WicPixelFormat = SharpDX.WIC.PixelFormat;
class Program
{
static void Main(string[] args)
{
var width = 400;
var height = 100;
var pixelFormat = WicPixelFormat.Format32bppBGR;
var wicFactory = new ImagingFactory();
var dddFactory = new SharpDX.Direct2D1.Factory();
var dwFactory = new SharpDX.DirectWrite.Factory();
var wicBitmap = new Bitmap(
wicFactory,
width,
height,
pixelFormat,
BitmapCreateCacheOption.CacheOnLoad);
var renderTargetProperties = new RenderTargetProperties(
RenderTargetType.Default,
new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown),
0,
0,
RenderTargetUsage.None,
FeatureLevel.Level_DEFAULT);
var renderTarget = new WicRenderTarget(
dddFactory,
wicBitmap,
renderTargetProperties)
{
TextAntialiasMode = TextAntialiasMode.Cleartype
};
renderTarget.BeginDraw();
var textFormat = new TextFormat(dwFactory, "Consolas", 48)
{
TextAlignment = TextAlignment.Center,
ParagraphAlignment = ParagraphAlignment.Center
};
var textBrush = new SolidColorBrush(
renderTarget,
Colors.Blue);
renderTarget.Clear(Colors.White);
renderTarget.DrawText(
"Hi, mom!",
textFormat,
new RectangleF(0, 0, width, height),
textBrush);
renderTarget.EndDraw();
var stream = new WICStream(
wicFactory,
"test.png",
NativeFileAccess.Write);
var encoder = new PngBitmapEncoder(wicFactory);
encoder.Initialize(stream);
var frameEncoder = new BitmapFrameEncode(encoder);
frameEncoder.Initialize();
frameEncoder.SetSize(width, height);
frameEncoder.PixelFormat = WicPixelFormat.FormatDontCare;
frameEncoder.WriteSource(wicBitmap);
frameEncoder.Commit();
encoder.Commit();
frameEncoder.Dispose();
encoder.Dispose();
stream.Dispose();
Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "test.png")));
}
}
}
Running this program gives you a "test.png" file in the program's working directory with the following beautiful image:
The question
Awesome, I've just rendered an image using Direct2D instead of GDI+, which is supposedly more supported in the context of an ASP.NET application. Plus, Direct2D is the new hotness.
Let's say that I wanted to write a function that rendered such an image and returned the PNG as a Stream or a byte[] array, performing the entire rendering and encoding operation in memory instead of writing to the file system. This is for a responding to a Web request; makes sense just to stream it out straight to the browser without going through the file system.
In GDI+, I could do this with a MemoryStream pretty easily, but I can't figure out how to use DataStream in SharpDX to my advantage without knowing the size of the buffer:
var bufferSize = 1024 * 3; // how do I know?
var buffer = new DataStream(
bufferSize,
true,
true);
var stream = new WICStream(
wicFactory,
buffer);
Do I have to P/Invoke to CreateStreamOnHGlobal and use that IntPtr to build my DataStream?
Is there some overload of DataStream that I am missing?
Is there an easy way to pre-calculate the necessary buffer needed to hold the encoded PNG image?
Or should I just get over going through the file system?
Thanks for any help!
The author of the library added this as a feature.
I'll leave the question around as I think the code provides a useful Direct2D sample for people.
If anyone is looking to do this in asp.net:
var memStream = new MemoryStream();
var wicStream = new WICStream(wicFactory, memStream);
//Encode wic bitmap
var encoder = new PngBitmapEncoder(wicFactory);
encoder.Initialize(wicStream);
var frameEncoder = new BitmapFrameEncode(encoder);
frameEncoder.Initialize();
frameEncoder.SetSize(width, height);
var format = WicPixelFormat.FormatDontCare;
frameEncoder.SetPixelFormat(ref format);
frameEncoder.WriteSource(wicBitmap);
frameEncoder.Commit();
encoder.Commit();
//Clean-up
frameEncoder.Dispose();
encoder.Dispose();
wicStream.Dispose();
imgBackdrop.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(memStream.ToArray(), 0, memStream.ToArray().Length);
I have a barCode class that is used to generate an image of a barCode. I create an instance of this class and it works as expected for example:
var myBarCodeInstance:barCode = new barCode();
var myBarCodeImg:Image = new Image();
myBarCodeImg.source = myBarCodeInstance;
Using this code the image appears and works fine. However, my question is how do I implement a loader on this image that will fire an event when the image is fully loaded and ready for processing? (I am running into null problems with the image not being fully loaded before attempting to access its contents).
Something like the below:
var loader:Loader;
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(e:Ev ent):void{
myBarCodeImg.source = e.currentTarget.content;
// further processing here
});
loader.load(new URLRequest(encodeURI(“image.jpg“)));
but i dont know what to insert in place of the "image.jpg" part due to my image being an instance of a class and not an actual jpg file.
Image dispatches a complete event - try listening for that event:
var myBarCodeInstance:BarCode = new BarCode();
var myBarCodeImg:Image = new Image();
myBarCodeImg.addEventListener(Event.COMPLETE, completeHandler);
myBarCodeImg.source = myBarCodeInstance;
function completeHandler(e:Event):void
{
var img:Image = e.currentTarget as Image;
var barcode:BarCode = img.content as BarCode;
/* process it */
}