React Native Image uri doesn't work - android

I tried to display an image from a local file, so I try to do this
<Image
source={{uri:'../../assets/img_src/BTI.jpg'}}
style={{height:150,width:150}}
/>
my container component seems getting the height and the width but the image doesn't load. So I try this
<Image
source={require('../../assets/img_src/BTI.jpg')}
style={{height:150,width:150}}
/>
It works really well, unfortunately as far as I know I can't use this implementation if i want to manipulate the address file first and store it to a variable.
Example:
const imgSrc = `../../assets/${data.image}`;
where the data.image = 'img_src/BTI.jpg'.
I try to delete all the data on my android simulator in the android studio but the result is still the same. Am I doing something wrong? Is there a better implementation for this?
Thanks a lot :)

Not being able to require() a dynamic path is an intended behaviour of React Native, the packager needs to know paths in advance - see React Native issues
We had this problem in our project, we were storing image URLs on our DB and wanted to concat strings in the app to get the path to the locally stored image. As you've discovered, this doesn't work. You might find our workaround useful.
In our /images folder, we created a new images.js file which simply exported an object whose keys mapped to all our local image paths like so
export const Images = {
image1: require('./image1.png'),
image2: require('./image2.png'),
image3: require('./image3.png'),
};
Now the packager knew all the paths in advance and was happy. Then we added an imageKey to the DB item and used this rather than the absolute path. To grab an image we simply did
import { Images } from '../images/images';
// get your image key e.g. passed down through props
const img = Images[imageKey];
...
render() {
...
<Image source={img} />
...
}
Might not fit your exact use case, but hopefully you might be able to make some use of it.

Related

Ionic 3 File Permissions

Alright, here goes. I'm dealing with an ionic project. In this specific scenario we're dealing with testing the Android version of the app. I can get images from the file system just fine, they come back in the form of a string url that looks something like this,
content://com.android.providers.media.documents/document/image%3A5744
The processor that is then supposed to blob the file and pass it up the line looks like this:
return this.file.readAsArrayBuffer(urlData.url, urlData.fileName)
.then((item) => {
return new Blob([new Uint8Array(item)]);
})
.catch((err) => {
console.log(err.message)
}).then((res)=>{
return new Blob([res])
})
But then I get the error SECURITY_ERR, which the documentation doesn't really talk about.
This works just fine for the pictures I take with the camera, which all have urls that look like this
file:///storage/emulated/0/Android/data/<appname>/cache/1502211622334.jpg
The issue is, as far as i can find, there is no documentation on what causes this error. I have no idea what to change to make my code work. I have verified the URI is valid, using the checkFile method.
So it turns out you can't use content urls with file.readAsArrayBuffer instead you have to first resolve the url into something readAsArrayBuffer can understand. To do this, i used the ionic native filePath plugin.
Once it was installed and included in the page where I needed it, I used the
filePath.resolveNativePath(url)
method on my url, since this returns a promise, I chained my readAsArrayBuffer onto a then statement prepended to it. I did have to use an if statement to have branching paths for content urls (Which required resolveNativePath) and non-content urls which were already working.
This solution works as far as I can tell.

React Native LruCache: Does it cache images from image urls

Basically, I am making an API call to get some kind of response back. In this response, there is some field like socialImageUrl that points to a URL string that references an image. There is other data there besides the URL. I am caching that entire response.
So I turn off wifi and LTE, and I checked that I had no internet connection by doing stuff on the browser. I go back into my app and I trigger my LruCache and retrieved the cached response (I know I got it because of logging) and I use that response to render my page.
What I expected: I would see all the data that I cached on the page but anything that used the image URLs will give out some erroneous image or maybe the page doesn't even load at all because there is some error with that image URL seeing as it can't access the internet
What actually happens: I see all of the data I cached and I also see the images
Any clue to what is going on? I'm not doing any image caching as far as I know. I am using react-native's vanilla Image JSX component. I am also on Android.
I was also in this situation ones, sadly React-Native docs are not extensive for now.
The Android implementation of Image component has by default caching enabled for images of low size < 500 KB (the max size is not documented but you can just try images of varied size to check and this size could change in the future).
Note: Even in IOS the image's will be cached by default when using the Image component.
If I had to guess, lru cache does not support caching binary data like an image file.
If you need advanced <Image> performance caching or for the remote image to be permanently stored to local disk for offline app use you can use my higher order component module that upgrades native <Image>
React Native Image Cache HOC
Tl;DR Code Example:
import imageCacheHoc from 'react-native-image-cache-hoc';
const CacheableImage = imageCacheHoc(Image);
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<CacheableImage style={styles.image} source={{uri: 'https://i.redd.it/rc29s4bz61uz.png'}} />
<CacheableImage style={styles.image} source={{uri: 'https://i.redd.it/hhhim0kc5swz.jpg'}} permanent={true} />
</View>
);
}
}
The first image will be cached until the total local cache grows past 15 MB (by default) then cached images are deleted oldest first until total cache is below 15 MB again.
The second image will be stored to local disk permanently. People use this as a drop in replacement for shipping static image files with your app, but you could use it so that your app displays image content even when user is offline.
If you need to grab all the image files from the network up front (before the <CacheableImage> is rendered by react native) then just use the following CacheableImage static method to pre-fetch the files:
import imageCacheHoc from 'react-native-image-cache-hoc';
const CacheableImage = imageCacheHoc(Image);
CacheableImage.cacheFile('https://i.redd.it/hhhim0kc5swz.jpg', true)
.then( localFileInfo => {
console.log(localFileInfo);
// Console log outputs:
//{
// url: 'https://i.redd.it/rc29s4bz61uz.png',
// cacheType: 'permanent',
// localFilePath: '/this/is/absolute/path/to/file.jpg'
//}
});

How can I load resourcesting

I am using XE7 Rad Studio to build "apps" for Android and IPhone. Focusing on Android for the moment.
According to the requirements, I need to load the HTML inside the application as a resource string.
WebBrowser1.LoadFromStrings(ResourceStrings.HTMLString,'');
//Loads the resource-string successfully.
However in this resource-string I need to load images, and I cant figure out how to do it. I can see in deployment that I have the images loaded into the project {Bitmap_1, Bitmap_2,Bitmap_3}.
How do I complete this line:
resource-string:
...'<img id="img2" class="thumbnail" src="/images/im2.bmp" alt="/images/im2.bmp"/>'...
Many thanks.
If you read the documentation for LoadFromStrings(), it says:
Displays HTML string content within the TWebBrowser component.
This method uses the following parameters:
Content: specifies the HTML string to be displayed.
BaseUrl: specifies a path that is used to resolve relative URLs within the loaded page. To clarify, consider the following scenario: this parameter is set to www.mycompany.com/departments/, and the loaded page defines a link <a href=’Sales.html’>Sales dept</a>. In the given case, clicking this link opens http:// www.mycompany.com/departments/Sales.html.
That is the exact scenario you are running into. Your HTML contains relative links to external images, but you are not providing a BaseURL, so the WebBrowser cannot resolve the correct URLs it needs to load those images.
In the Deployment Manager, set the Remote Path of your image files to either StartUp/Documents/images/ or StartUp/Library/Application Support/images/.
At app startup, Delphi will copy files beginning with StartUp to the appropriate folder on the device. Then you can do the following when calling LoadFromStrings():
// note sure which function to use for 'StartUp/Library/Application Support/',
// maybe TPath.GetLibraryPath()? This example is for '/StartUp/Documents/'...
WebBrowser1.LoadFromStrings(ResourceStrings.HTMLString, 'file://' + TPath.GetDocumentsPath);
That will allow "/images/im2.bmp" to resolve to something like file:///data/data/<application ID>/files/images/im2.bmp", etc.

How can a json file read in Android using Ionic and AngularJS Frameworks?

I have a problem now regarding about the json that can't be read in my android..
the json file is where my data is place..it act as an static database..
I can get it with my Desktop but when it come to my mobile it didn't show..
Here is my sample code:
Here is my Services to get my json file..
var serviceUrl = '/';
$http.get(serviceUrl + 'JSON/Books.json').success(function (results) {
$scope.New = results;
});
Please help me to solve this problem.. my idea about the problem is the serviceUrl. Any idea about it. Thank you so much..
Im definitely a beginner for this Ionic Framework.
To all who still in this problem I just find something that solve it. I don't know if it will solve in your problem but it really solve in me.. I use file:///android_asset/www/ as my serviceUrl
So this is an example:
var serviceUrl = 'file:///android_asset/www/';
$http.get(serviceUrl + 'JSON/Books.json').success(function (results) {
$scope.New = results;
});
Just try it and explore to it.. i just tried that one and it worked in me..
Maybe the reason is the all the json file in your apk installer will be placed in file:///android_asset/www/json directory in android phone so let your url point to that directory..
I hope it will help you and explore in it..that might not be the correct answer but i hope it will help you find the hint.
Thank you
Starting the serviceUrl with a '/' makes it an absolute URL. It will work in chrome since the root is the www folder. But in cordova mobile environment it will translate to file:///.
Simply add a '.' ('./') to make it a relative path and it will work in both android and ios environments.
another easy way is to turn your json file into a javascript file, (for static files if you want to update use something like pouchdb).
eg save the json document as myjsondata.js
var mynamespace = mynamespace || {};
mynamespace.data = [{"foo":"bar"}];
then reference the javascript file in you main page where you load all the other js files
<script src="js/myjsondata.js"></script>
then in your service you can just access the json with mynamespave.data
Based on #Datz Me answer, I've found it's way easier if you treat your application as a web server (which it is) and request your file as being served by it instead of trying to figure out how to manage the different file paths between the several builds.
Here is what I did.
I've placed my json file on
www/json/app.json
Inside it I've put
{
"title": "Application Title",
"icon" : "custom-icon.png"
}
And in my app controller I used the following code to read the properties:
$http.get('json/app.json').success(function (results) {
$rootScope.title = results.title;
$rootScope.icon = results.icon;
});
And in all my child controllers, I just need to add $rootScope as a dependency and I'm able to use
{{title}} //on headings
{{icon}} //to display the image path
<img src="{{icon}}"/> //to display the icon
In my case, it's an app that will be customised for several clients, so I needed a way to quickly change the app's properties and keep them in one place.

do i need to load jpg file for flex air mobile projects like as3?

In a typical as3 or flex project, after loading xml file, i load jpg files (thumbnails etc) manually, so i can use them in sprites / movie clips etc..
currently i am working on air mobile project. and i am attempting to load some thumnails(jpg) file to list view (spark) and using custom item renderer.
itemrenderer has an spark image component in it. and its data property is set to Image object.
i can check that image files do exists in file application directory.
do i need to load all those thumbnails in memory. then use them?
image object will autoload source file object?? once assigned?
do i have to tell it explicitly to load file object? what events should i use to amke sure , image file object is loaded.?
any ideas?
thanks in advance.
Spark images are really easy to work with. All you need is a url.
<s:Image source="http://someimagesite.com/someimage.png" width="100%" height="100%" />
You can also use bitmap data or even embed directly into the source tag.
[Embed(source="image.png")] private var myImage:Class
mySparkImage.source = new myImage() as BitmapData;
<s:Image source="#Embed('image.png')" />
Take a look:
http://help.adobe.com/en_US/flex/using/WSc5cd04c102ae3e97-33ad5caa12c719dc7c8-8000.html

Categories

Resources