Why use ImageSource.FromStream instead of FromFile in Xamarin Media plugin? - mobile

I am using James Montemagno's Xamarin Media Plugin (https://github.com/jamesmontemagno/MediaPlugin) and his usage example shows an image being updated in this way from the captured photo:
targetImage.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
This seems to work just as well:
targetImage.Source = ImageSource.FromFile(file.Path);
However I feel that James' example must be showing a better way but I can't figure why -- maybe some subtle thing on one platform or another. Can anyone tell me why the Xamarin ImageSource should be set one way versus another?

The reason for choosing either FromFile() or FromStream() depends on the use case at hand. Also, the methods used depend on the data type as documented here.
WhereasFromFile() requires a string to a path, FromStream() requires a Func<System.IO.Stream>.
In the specific case you mention, and the sample hereof, it is sensible to return a Stream since a photo is being taken which is not yet stored.
First, TakePhotoAsync() is called which returns a MediaFile. This class then returns a Stream when calling GetStream(). Afterwards, the Source of the Image is set to the result.
In essence, the approach you decide on depends on the use case and data type at hand.

Related

To check if an image file exists and load another default file if not

In my developing with React, I encounter this problem:
I retrieve certain data from a remote API with relevant information to describe a book: http://api.rsywx.com/book/randomBook/1. This will return a JSON string:
{"status":200,"out":[{"bookid":"00637","title":"\u4e2d\u56fd\u53e4\u4ee3\u601d\u60f3\u53f2","author":"\u6768\u8363\u56fd","region":"\u4e2d\u56fd\u5927\u9646","purchdate":"1973-09-13"}]}
Out of this return, I populate a state object and to display that book in the page.
One thing is that I need to display a book cover associated with that book. I don't have covers for all my books stored in (and thus randomly returned from) the API.
If a cover image is there, I can safely display that image via:
<img
className="ls-l"
src={this.state.cover}
.../>
cover is populated from bookid.
But if not, I must display a default.jpg as a fallback.
So basically I need to check if this.state.cover file exists.
Any input will be much appreciated.
Update
Thanks for all's input below.
I think it may be that I did not make my self clear.
No matter whether the image file exists in my server side, this.state.cover will be populated from bookid, i.e, in the form of "http://myserver/img/12345.jpg", where 12345 is the bookid.
The real situaion is that file 12345.jpg exisits, but 54321.jpg is not.
So before I display the image in my <img> tag, I have to replace 54321.jpg to default.jpg. I think this is a question related to file manupilation.
The below methods are assuming cover field is not set, which is not the case in my code.
Nevertheless, thanks all.
Two different ways:
let {cover = "fallback.jpg"} = this.state;
Or
src={this.state.cover || "fallback.jpg"}
Or you use the monadic goodness of functional programming to get rid of the null checks.
fetch(url,{})
.then( (response)=> response.json())
.then((book) => this.setState({
picture: book.picture || defaultCover.jpg
}))
You can go with the usual || operator here. This would work fine. But be sure of the ordering. In pic1 || pic2 pic1 is checked first. If it is undefined, it goes for pic2.
Use conditional operator to check if cover property exists or not. Use something like this,
const defaultImage = "some-url";
<img
className="ls-l"
src={this.state.cover ? this.state.cover : defaultImage}
.../>

How do I store dynamically a movieclip in a array in Haxe/HTML5?

This is my code:
var buttons:Array<Dynamic> = new Array<Dynamic>();
var mc2:flash.display.MovieClip = new MovieClip();
mc2.graphics.beginFill(0xFF0000);
mc2.graphics.moveTo(50,50);
mc2.graphics.lineTo(100,50);
mc2.graphics.lineTo(100,100);
mc2.graphics.lineTo(50,100);
mc2.graphics.endFill();
buttons.push(addChild(mc2));
buttons[0].x = 1000;
And my question is why this work in Flash but not work in HTML5 when I compile it? How do I solve the problem?
The last line “buttons[0].x = 1000;” is not working in HTML5… :/
Sorry for my english...
Because you use in "flash.display.MovieClip" class that does not available from HTML5.
In Haxe, if you use in class that belongs to specific target (like MovieClip) you can compile it only to that target.
Maybe you will found OpenFl library useful, It's library that let you develop with Flash API and target to almost any device(and also for HTML5) from same base code!
see Here for more
Are you using a framework?
Maybe it works if you split the addChild and the push into separate lines? Not sure if addChild returns a MovieClip?
Otherwise, try to trace the array trace(buttons) and observe the browser console.

How to use phloc schematron-pure with Document -schema-definition

This question concerns phloc-schematron, a library for ISO Schematron validation.
I am creating schematron-files on the fly, so I have them available as document (or as string of course)
I cannot find a constructor for SchematronResourcePure that takes a string or document as argument, nor can I find a method to create a IReadableResource from the same.
Can someone suggest how to do this?
In case this is still relevant:
Switch to ph-schematron at https://github.com/phax/ph-schematron/ and use the static SchematronResourcePure.fromString method.
But you are right - this is a case that is currently not considered - building the Schematron from scratch. I will see, what I can do!

EXTJS - How to verify if element exists?

I need to know if a boxComponent exists in a ext formPanel in order to take some actions... Is there some way to know that?
something like this:
if(getElementById("boxId") != 'undefined' ){
alert('exists');
}
The common pattern that most people use is this:
var myBoxCmp = Ext.getCmp('cmpId');
if(myBoxCmp){
myBoxCmp.doSomething();
}
Same thing for Elements:
var el = Ext.get('elId');
if(el){
el.doSomething();
}
You can also use methods like Container.findById, but if you have an id (assuming it is unique, which it should be) just use getCmp.
EDIT: Several years have passed since this original answer, and nowadays getCmp is generally frowned upon as a code smell and should typically be avoided in applications (promotes global references, which generally indicate poor design when they are required). It's typically better to use controller references (if using MVC) or the various ComponentQuery or Container methods to reference related components (e.g. down, child, getComponent, etc.)
I just do it the extjs way and i prefer not to use getElementById() which is a native js method and may cause incompatibility issues in diffrenet browsers:
if (!Ext.getCmp('componentid')) {
alert('boxId is empty');
}
You can use Ext.get('boxId'). It returns null if the object doesn't exist and returns an Ext.Element object.
Using getElementById would probably be much faster though. Do you have any specific objection against it?
Use the Ext.isEmpty(object) method.
if(Ext.isEmpty(getElementById("boxId")) {
alert('boxId is empty');
}
function openView(cid) {
shortName = cid.substr(cid.lastIndexOf(".")+1, cid.length);
if(Ext.get(shortName) == null) Ext.create(cid);
Ext.Viewport.setActiveItem(Ext.getCmp(shortName));
}
This function opens a view like
openView('MyApp.view.Oeffnungszeiten');
and if the View exists it accesses the old instance

How do I detect whether the sample supplied by VideoSink.OnSample() is right-side up?

We're currently using the Silverlight VideoSink to capture video from users' local webcams, kinda like so:
protected override void OnSample(long sampleTime, long frameDuration, byte[] sampleData)
{
if (FrameShouldBeSubmitted())
{
byte[] resampledData = ResizeFrame(sampleData);
mediaController.SetVideoFrame(resampledData);
}
}
Now, on most of the machines that we've tested, the video sample provided in the byte[] sampleData parameter is upside-down, i.e., if you try to take the RGBA data and turn it into, say, a WriteableBitmap, the bitmap will be upside-down. That's odd, but fairly easy to correct, of course -- you just have to reverse the array as you encode it.
The problem is that at least on some machines (e.g., the single Macintosh in our test environment), the video sample provided is no longer upside-down, but right-side up, and hence, flipping the image actually results in an image that's received upside-down on the far side.
I reported this to MS as a bug, but their (terse) response was that it was "As Designed". Further attempts at clarification have so far been ignored.
Now, I'll grant that it's kinda entertaining to imagine the discussions behind this design decision: "OK, just to make it interesting, let's play the video rightside up on a Mac, but let's turn it upside down for Windows!" "Great idea!" "Yeah, that'll keep those developers guessing!" But beyond that, I can't find this, umm, "feature" documented anywhere, nor can I find any documentation on how one is supposed to be able to tell that a given video sample is upside down or rightside up. Any thoughts on how to tell this?
EDIT 3/29/10 4:50 pm - I got a response from MS which said that the appropriate way to tell was through the Stride property on the VideoFormat object, i.e., if the stride value is negative, the image will be upside-down. However, my own testing indicates that unless I'm doing something wrong, this isn't the case. At least on my own machine, whether the stride value is zero or negative (the only options I see), the sampled image is still upside-down.
I was going to suggest looking at VideoFormat.Stride provided at VideoSink.OnFormatChange but then I noticed your edit. I went ahead and tested it at my dev machine, image is upside down and stride is negative as expected. Have you checked again recently?
Even though stride made perfect sense for native applications (using stride at pointer operations), I agree that current behavior is not what you expect from a modern API. However performance wise, it is better not to make changes on data received from native API.
Yet at this point, while we are talking about performance, why not provide samples in formats other than PixelFormatType.Format32bppArgb so that we can avoid color space conversion? BTW, there is a VideoCaptureDevice.DesiredFormat property which only works for resolution as there is no alternative to PixelFormatType.Format32bppArgb.

Resources