How to load an image in Dart - dart

I'm trying out the Dart Language and HTML5 Canvas element, but I'm stuck with one problem. I don't know how to load an image in Dart. I can get CanvasRenderingContext2D and with this I can call fillText() and fillRect() and everything works, but I am trying to figure out how to load an Image and draw with drawImage.

Create and load the image
ImageElement image = new ImageElement(src: "my_image.png");
image.onLoad.listen((e) {
// Draw once the image is loaded
});
Draw the above image on the canvas after it is loaded
context.drawImage(image, destX, destY);

Newer image onload syntax:
readFile() {
ImageElement image = new ImageElement(src: "plant.png");
document.body.nodes.add(image);
image.onLoad.listen(onData, onError: onError, onDone: onDone, cancelOnError: true);
}
onData(Event e) {
print("success: ");
}
onError(Event e) {
print("error: $e");
}
onDone() {
print("done");
}

This is another way to do it :
void main() {
ImageElement image = new ImageElement(src: "pic.png");
img.onLoad.listen(onData);
img.onError.listen(onError);
}
void onData(Event e) {
print("Load success");
}
void onError(Event e) {
print("Error: $e");
}

Related

How do I check the size of the data file before I upload it (Flutter)

When I take the file I want the data file size information, in the future the upload file limit will be made based on the file size. the following code that I use
void _openFileExplorer() async {
setState(() => _loadingPath = true);
try {
_directoryPath = null;
_paths = (await FilePicker.platform.pickFiles(
type: _pickingType,
allowMultiple: _multiPick,
allowedExtensions: ['jpg', 'pdf', 'doc', 'docx', 'png', 'jpeg'],
))
?.files;
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
} catch (ex) {
print(ex);
}
if (!mounted) return;
setState(() {
_loadingPath = false;
_fileName = _paths != null ? _paths.map((e) => e.name).toString() : '...';
});
}
you can get file size using function named lengthSync.
just use this function like
var size = file.lengthSync()
it will give file size in bytes.

Gluon iOS audio Player

I've been following various answers to various questions on the subject and I've come to a result and some code which looks like it works. I'm getting stuck with the NSURL part of it. I've got 2 mp3 tracks in the assets folder of my iOS gluon project. I've made the IOSAudioService Class to handle the playback. and I'm passing an argument from the play button in the view to the Play() method. Everything other than the actual file is registering as working. I'm getting an NSError, which from looking at the code is a nil value, so either the argument isn't passing correctly or it can't find the file. Code below.
public AVAudioPlayer backgroundMusic;
private double currentPosition;
NSURL songURL = null;
#Override
public void Play(String filename){
songURL = new NSURL(filename);
try {
if (backgroundMusic != null) {
Resume();
}
else {
//Start the audio at the beginning.
currentPosition = 0;
backgroundMusic = new AVAudioPlayer(songURL);
//create the mendia player and assign it to the audio
backgroundMusic.prepareToPlay();
backgroundMusic.play();}
//catch the audio error
} catch(NSErrorException e) {
System.out.println("error: " + e);
}
}
#Override
public void Stop() {
backgroundMusic.stop();
backgroundMusic = null;
}
#Override
public void Pause() {
currentPosition = backgroundMusic.getCurrentTime();
backgroundMusic.pause();
}
#Override
public void Resume() {
backgroundMusic.setCurrentTime(currentPosition);
backgroundMusic.play();
}
try {
services = (AudioService) Class.forName("com.gluonhq.charm.down.plugins.ios.IOSAudioService").newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
System.out.println("Error " + ex);
}
I'm getting the error at the catch block for NSExceptionError e.
if (services != null) {
final HBox hBox = new HBox(10,
MaterialDesignIcon.PLAY_ARROW.button(e -> services.Play("/audio.mp3")),
MaterialDesignIcon.PAUSE.button(e -> {
if (!pause) {
services.Pause();
pause = true;
} else {
services.Resume();
pause = false;
}
}),
MaterialDesignIcon.STOP.button(e -> services.Stop()));
//set the HBox alignment
hBox.setAlignment(Pos.CENTER);
hBox.getStyleClass().add("hbox");
//create and set up a vbox to include the image, audio controls and the text then set the alignment
final VBox vBox = new VBox(5, Image(), hBox, text1);
vBox.setAlignment(Pos.CENTER);
setCenter(new StackPane(vBox));
} else {
//start an error if service is null
setCenter(new StackPane(new Label("Only for Android")));
}
Services.get(LifecycleService.class).ifPresent(s -> s.addListener(LifecycleEvent.PAUSE, () -> services.Stop()));
}
I've also follow the advice on creating the service factory class and the interface from Audio performance with Javafx for Android (MediaPlayer and NativeAudioService) taking out the add audio element and I'm intending to do this on a view by view basis if possible.
Problem solved after must fiddling and looking in the Javadocs.Solved by adding/replacing some code with the below.
songURL = new NSURL("file:///" + NSBundle.getMainBundle().findResourcePath(filename, "mp3"));
try {
songURL.checkResourceIsReachable();}
catch(NSErrorException d) {
System.out.println("Song not found!" + d);
}

MonoDroid Get Full Image Path, OnActivityResult

Using OnActivityResult, how do I get the full path of an image? I am using OnActivityResult and I get get a Bitmap. Can I load that info a file somehow? Here is my code:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
try
{
base.OnActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case REQUEST_IMAGE:
if (resultCode == Result.Ok)
{
//Bitmap thumbnail = (Bitmap)data.Extras.Get("data");
//imagePicture.SetImageBitmap(thumbnail);
}
break;
default:
break;
}
}
catch (System.Exception ex)
{
}
}
You could do something like this to write the image out to a file:
var bitmap = (Android.Graphics.Bitmap)data.Extras.Get("data");
using (var stream = File.Create("/path/to/file"))
{
bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, stream);
}

Canon EDSDK ObjectEvent_DirItemRequestTransfer

My C# application is shooting an image every 3 minutes and I get the image from the EDSDK as expected every time. My problem is that the application is leaking about 5 mb for every shot and Iøm very sure that the problem is the EDSDK.
Code:
private uint CameraObjectEvent(uint inEvent, IntPtr inRef, IntPtr inContext)
{
switch (inEvent)
{
case EDSDK.ObjectEvent_DirItemRequestTransfer:
GetCapturedItem(inRef);
break;
}
return EDSDKErrorCodes.EDS_ERR_OK;
}
private void GetCapturedItem(IntPtr directoryItem)
{
uint error = EDSDKErrorCodes.EDS_ERR_OK;
IntPtr stream = IntPtr.Zero;
//Get information of the directory item.
EDSDK.EdsDirectoryItemInfo dirItemInfo;
error = EDSDK.EdsGetDirectoryItemInfo(directoryItem, out dirItemInfo);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsGetDirectoryItemInfo failed.");
return;
}
//Create a file stream for receiving image.
error = EDSDK.EdsCreateMemoryStream(dirItemInfo.Size, out stream);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsCreateMemoryStream failed");
return;
}
//Fill the stream with the resulting image
error = EDSDK.EdsDownload(directoryItem, dirItemInfo.Size, stream);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsDownload failed.");
return;
}
error = EDSDK.EdsDownloadComplete(directoryItem);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsDownloadComplete failed.");
return;
}
//Copy the stream to a byte[]
IntPtr pointerToBytes = IntPtr.Zero;
EDSDK.EdsGetPointer(stream, out pointerToBytes);
MemoryStream imageStream = null;
Image image = null;
try
{
byte[] buffer = new byte[dirItemInfo.Size];
GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Marshal.Copy(pointerToBytes, buffer, 0, (int)dirItemInfo.Size);
//Create a MemoryStream and return the image
imageStream = new MemoryStream(buffer);
image = Image.FromStream(imageStream);
}
catch (Exception ex)
{
OnCameraErrorRaised(999999, string.Format("Failed while retrieving image from camera. Exception: {0}.", ex.Message));
}
finally
{
if (imageStream != null)
imageStream.Dispose();
}
//If image was captured then send ImageCaptured event
if (image != null)
OnImageCaptured(image);
//Clean up
EDSDK.EdsRelease(pointerToBytes);
pointerToBytes = IntPtr.Zero;
EDSDK.EdsRelease(stream);
stream = IntPtr.Zero;
EDSDK.EdsRelease(directoryItem);
directoryItem = IntPtr.Zero;
}
The line OnImageCaptured(image) just sends the image to a controller which merges the image from the camera with another image and then disposes both images after saving the finale merged image:
private void ImageCaptured(Image originalImage)
{
Image watermark = null;
//Merge images
try
{
watermark = Image.FromFile(Settings.Default.ImageWatermarkFilename);
_imageController.Merge(originalImage, watermark);
_imageController.SaveImage(originalImage);
}
catch (Exception ex)
{
LogManager.Instance.UpdateLog(string.Format("Error - Failed to merge and save images. Exception: {0}.", ex.Message));
//HACK:
System.Windows.Forms.Application.Restart();
App.Current.Shutdown();
}
finally
{
originalImage.Dispose();
if (watermark != null)
watermark.Dispose();
}
}
So why does the app memory leak - any ideas?
/Cheers
release your GCHandle. it is the culprit eating memory every time when you are taking shoot
gcHandle.Free()

problems in silverlight 4 when using Action callbacks to check for successful file upload

So the async requirement for silverlight ends up in some really convoluted code!!
Im uploading a file just exactly like this answer suggests.
The difference is Im posting the file to an MVC action method. Everything works file except, like I commented on the bottom of that answer, I don't get any callback for when the file DOES NOT successfully upload.
So I created another action method in my mvc app (Services/CheckForFile/{id}) and it returns a string depending on whether the file is found.
Now, how and when do I call this mvc action method is the problem:
void DoUpload() { //Gets call on BtnUpload.Click
//opn is an OpenFileDialog
up.UploadFile(_filename, opn.File.OpenRead(),
e =>
{
//do some ui stuff here.
BeginCheck();// calling this causes PROBLEMS!
});
}
private void BeginCheck()
{
Uploader up = new Uploader();
up.CheckForFile(_filename, success =>
{
if (!success)
{
MessageBox.Show("There was problem uploading the file. Please try again", "Error", MessageBoxButton.OK);
}
});
}
Here is the problem:
When the BeginCheck() function runs, the file, for some reason, NEVER uploads! If I comment it out it does!? It seems like The BeginCheck() runs during the upload or something? Shouldn't it run after!?
How/where would I call BeginCheck() after the upload, to ensure the file has been uploaded?
Here is how I defined the Uploader class:
public class Uploader
{
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
callback(null);//this ALWAYS hits!
}
catch (Exception err)
{
if (callback != null)
{
callback(err);
}
}
};
c.OpenWriteAsync(ub.Uri);
}
public void CheckForFile(string filename, Action<bool> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/CheckForFile/" + fileName);
WebClient c = new WebClient();
c.OpenReadCompleted += (sender, e) =>
{
using (StreamReader sw = new StreamReader(e.Result))
{
if (sw.ReadToEnd().Equals("Found", StringComparison.InvariantCultureIgnoreCase))
{
callback(true);
}
else
{
callback(false);
}
}
};
c.OpenReadAsync(ub.Uri);
}
private void PushData(Stream input, Stream output)
{//4KB is not a limitation. We only copy 4Kb at a time from in to out stream
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
I'm embarrased to say that the original answer of mine to which you refer isn't entirely accurate. It seems to work for what the OP wanted but in fact the code doesn't block at the point that I thought it did. In reality what you are actually looking for is the WriteStreamClosed event, its here that you can discover any failure of the request.
Here is an ammended version that works the way you are expecting:-
public void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder(_mvcurl+"Services/UploadFile/" + fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); //this does not block.
}
catch (Exception err)
{
if (callback != null)
callback(err);
}
};
c.WriteStreamClosed += (sender, e) =>
{
if (callback != null)
callback(e.Error);
}
c.OpenWriteAsync(ub.Uri);
}
Now your BeginCheck will only run after the server has responded to the file upload.

Resources