React Native - Prepare Images before rendering - image

I have been struggling for the past couple of days figuring out a good approach to my problem. I need to display an < Image> component one at a time (Requirement, so ListView is not an option). This component has as source an uri that points to a firebase image. I am trying to prepare on componentWillMount an array that contains all the component Images that will be displayed such as:
let mediaArray = this.props.list.map(function(media){
return <Image style={styles.imageStyle} source={{uri: media}} />;
});
this.setState({list: mediaArray});
However, when I try to display a specific image on that array on the render function I still need to wait a couple of seconds to see the image.
render(){
{this.state.list[currentIndex]}
}
If it was previously prepared, why does it tries to obtain the image again? This suggest that React only looks for the source when is rendering only?
You can say that I am trying to create a "Feed" (Like instagram, facebook, etc), but is not conventional because I need to display one Image Component at a time.
I also tried looking into cache images, but that will not help me because in reality I will be trying to obtain hundreds of images.

you are on the money with the realization that React Native will not fetch the sources for your images until they are rendered. If you want to preload the images you will have to call prefetch on the image source. A simple example using your code would be to modifywhere you create mediaArray to look like this:
let mediaArray = this.props.list.map(function(media){
Image.prefetch(media); // that's it!
// you can now remove this following line and just construct a single image tag later.
return <Image style={styles.imageStyle} source={{uri: media}} />;
});
this.setState({list: mediaArray});
if you want to be a bit more clever you could prefetch only a few of the upcoming images each time currentIndex is updated. If you need more guidance please share more of this component's code.
Hope this helps!

Related

`filter.applyTo is not a function` error when try to change image src using setSrc() in fabric js

Currently, I am Working on image editor that allows me to crop an image and apply a filter.
I am using fabric js version 1.7.22.
I want to implement crop functionality.
so my cropping flow is like Below :
crop image using a plugin and ger base64 of the cropped image.
generate blobUrl from base64 which help to display image in fabric js canvas.
After Cropping the image, I Just replace old image src with new One.
It works fine when an image has no filter.
but when I try to set a filter in the image first then try to replace src using setSrc() function.
It throws an error like Below
filter.applyTo is not a function
I have created one fiddle for demonstrating to replace src after the apply filter.
https://jsfiddle.net/Mark_1998/98gLhcb4/1/
And I Can't upgrade my fabric js version. If any patch Available then
Please Help Me.
The problem lies in this piece of code:
canvas.getActiveObject().setSrc('http://fabricjs.com/assets/pug_small.jpg', function(){
canvas.renderAll();
}, canvas.getActiveObject().toObject());
You're passing canvas.getActiveObject().toObject() as an options object, which is assigned to your image in setSrc() -> setElement() -> _initConfig().
toObject() serializes your fabric.Image, and filters array no longer contains the actual fabric.Filter, but rather a serialized version of it. So, it does not have a prototype with applyTo() method on it, hence the error filter.applyTo is not a function when fabric tries to reapply filters to your image after setSrc().
Instead of passing the whole serialized object as options, you'll need to pick the properties you actually want to be passed. As I'm not sure about what your requirements are, I tried replacing the above code with the following and it worked for me:
var options = canvas.getActiveObject().toObject();
delete options.filters;
options.crossOrigin = true;
canvas.getActiveObject().setSrc('http://fabricjs.com/assets/pug_small.jpg', function(){
canvas.renderAll();
}, options);
Note the options.crossOrigin = true - you won't be able to apply filters without it.

Image.prefetch not automatically loading from cache [React-Native / Expo]

I am trying to understand how to cache an Image url so that it does not need to be redownloaded.
I have taken a look at: https://docs.expo.io/versions/v19.0.0/guides/preloading-and-caching-assets.html
and have been using Image.prefetch like so:
const prefetchedImages = images.map(url => {
console.log('url', url) //this is correctly logging the url
return Image.prefetch(url)
});
Promise.all(prefetchedImages)
.then(() => {
this.setState({loaded:true})
})
This ultimately does set the state as true. I am then rendering my Images in a different component, but I make sure the component that is prefetching does not unmount. I load the url like so:
<Image source={{uri: myImageUrl}} style={{width:100, height:100}} />
When I load images into my grid view, only the local images appear right away, and the ones with URLs are white for a moment before rendering. When using cache:‘force-cache’ on iOS, the images are in fact loaded from cache and there is no lag. I thought I did not need to do that if I used prefetch.
Am I missing something here? I thought I can call my Image source as usual and the system will know how to grab the cached image for that url.
I do not think prefetch is quite as simple as just loading the image from cache just because it is in the cache, if that makes sense.
Check out this thread https://github.com/facebook/react-native/issues/2314 and this question React native Image prefetch.
If you want to save images and have them always available offline look at https://www.npmjs.com/package/react-native-preload-images.

Nativescript Loading Images

Here is my scenario: On my main view I am loading a list of items. Each item has an imageURL property. I am binding an Image component to the ImageURL property. Everything works well, but the image takes an extra second or two to load during which time the Image component is collapsed. Once the image is loaded, the Image component is displayed properly. This creates an undesirable shift on the page as the image is rendered.
The same images are going to be rendered on 2 other views.
What is the best practice to handle this scenario? I tried loading the base 64 string instead of the image url, which worked, but it slowed down the loading of the initial view significantly.
How can I pre-fetch the images and reuse them as I navigate between the views? I was looking at the image-cache module which seems to be addressing the exact scenario, but the documentation is very vague and the only example I found (https://github.com/telerik/nativescript-sample-cuteness/blob/master/nativescript-sample-cuteness/app/reddit-app-view-model.js) did not really address the same scenario. If I understood the code correctly, this is more about the virtual scrolling. In my case, I will have only 2-3 items, so the scrolling is not really a concern.
I would appreciate any advise.
Thank you.
Have you tried this?
https://github.com/VideoSpike/nativescript-web-image-cache
You will likely want to use a community plugin for this. You can also take a look at this:
https://docs.nativescript.org/cookbook/ui/image-cache
So after some research I came up with a solution that works for me. Here is what I did:
When the app start I created a global variable that contained a list of observable objects
then I made the http call to get all the objects and load them into the global variable
In the view I displayed the image as (the image is part of a Repeater item template):
<Image loaded="imageLoaded" />
in the js file I handled the imageLoaded events as:
var imageSource = require("image-source");
function imageLoaded(args) {
var img = args.object;
var bc = img.bindingContext;
if (bc.Loaded) {
img.imageSource = bc.ImageSource;
} else {
imageSource.fromUrl(bc.ImageURL).then(function (iSource) {
img.imageSource = iSource;
bc.set('ImageSource', iSource);
bc.set('Loaded', true);
});
}
}
So, after the initial load I am saving the imageSource as part of the global variable and on every other page I am getting it from there with the fallback of loading it from the URL is the image source is not available for this item.
I know this may raise some concerns about the amount of memory I am using to store the images, but since in my case, I am talking about no more than 2-3 images, I thought that this approach would not cause any memory issues.
I would love to hear any feedback on how to make this approach more efficient or if there is a better approach altogether.
You could use the nativescript-fresco plugin-in. It is an {N} plugin that is wrapping the popular Fresco library for managing images on Android. The plugin exposes functionality like: setting fade-in length, placehdler images, error images (when download is unsuccessful), corner rounding, dinamic sizing via aspect ration etc. for the full list of the advanced attributes you can refer this section of the readme. Also the plugin exposes some useful events that you can use to add custom logic when images are being retrieved from remote source.
In order to use the plugin simply initialize it in the onLaunch event of the application and call the .initialize() function:
var application = require("application");
var fresco = require("nativescript-fresco");
if (application.android) {
application.onLaunch = function (intent) {
fresco.initialize();
};
}
after that simply place the FrescoDrawee somewhere in your page and set its imageUri:
<Page
xmlns="http://www.nativescript.org/tns.xsd"
xmlns:nativescript-fresco="nativescript-fresco">
<nativescript-fresco:FrescoDrawee width="250" height="250"
imageUri="<uri-to-a-photo-from-the-web-or-a-local-resource>"/>
</Page>

How to show a loader until images are ready then show them

I am currently working on a website (http://thibaudjourdan.fr/). In the galleries, when your computer loads an image, it actually loads on the left of my screen and, once fully loaded, displays on the center like it should. I don't like this, is there a way to show some sort of loader instead of the image then show it once it's ready ?
I have seen some solutions on the internet but none seemed to fit my needs or i wouldn't get it to work, can anyone help ?
Thank you.
There is an onload event for images. That can be used to show it when its done
<img src="/path/to/image.jpg" onload="doStuff(this);" />
You can also manage from jQuery
$("img").one("load", function() {
// do stuff
})

How to retrieve images (decoded if possible) present in a wepage using XPCOM

How to get all the images, after decoding if possible, on a webpage through XPCOM ?
The image might be specified in HTML as a background url in some CSS property, inside img tag, or in any form that a web developer might have included.
I tried looking into imgIContainer, imgIDecodeObserver and many other interfaces. Although there is a way through which we can provide image URI to Mozilla so that it loads the image, decodes it and returns imgIContainer. But I couldn't find anyway to get all images in current webpage.
This has to be done in either Java or Javascript.
Any suggestions?
#Wladimir - Thanks for your help.
I want all the images including CSS constructs (background images). So now I am listening to events from nsIWebProgressListener.
onStateChange: function(webProgress, request, stateFlags, status) {
if ((~stateFlags & (nsIWebProgressListener.STATE_IS_REQUEST | nsIWebProgressListener.STATE_STOP)) == 0) {
var imgReq = request.QueryInterface(CI.imgIRequest);
if (imgReq)
var img = imgReq.image;
}
}
The problem is that request.QueryInterface(CI.imgIRequest) throws exception for all NON-image requests. Although those exceptions can be ignored by putting code inside try-catch block, but I'd prefer to do things cleanly.
Is there any condition that can be checked to know whether request is for image or not?
There is existing code that you can look at. The Page Info dialog has a Media tab that successfully shows most images on the page. The important function is grabAll() in pageInfo.js, it is called for each element (via a TreeWalker). As you can see, there is no generic way to get the image, this function rather uses window.getComputedStyle() to extract the values of a bunch of the CSS properties for this element: background-image, border-image, list-style-image, cursor. It will also look for <img>, <svg:image>, <link> (favicon), <input>, <button>, <object> and <embed> tags. It doesn't manage to recognize everything however, e.g. these CSS constructs will not be recognized:
.foo:before
{
content: url(image.png);
}
.foo:hover
{
background-image: url(image.png);
}
Still, this is probably as far as you can get - unless you want to look at the requests made by the web page as it loads.
Edit: If you look at the requests as they are performed (via a web progress listener), you can do the following:
if (request instanceof CI.imgIRequest)
var img = request.URI.spec;
Note that request.image won't help you much, almost all methods of imgIContainer are only accessible from native code.

Resources