React Native : Alternate way to get the Image require to work when array of image paths got dynamically from fetchapi - react-native

React Native : Alternate way to get the Image require to work when array of image paths got dynamically from fetchapi
Tried the below and aware that require always need the fixed path in quotes('') which works well when static image path is known. Thee should be alternate way to map the images which is received from fetchapi.
source={require('./assets/images/'+{item.image_path})}
Example fetch api json response is: [{user_name: 'DynamicUser1', image_path: 'DynamicUser1.jpg'},{user_name: 'TestUser1', image_path: 'TestUser1.jpg'}... ]
Need alternate way to get the images rendered with the dynamic image path rightly picked from the fetch api.
userData = this.state.resultsUserData.map((item) => {
return (
          <View key={item.user_name} style={ styles.container }>
            <Text style={styles.title}>
              {item.user_name}
            </Text> 
<TouchableOpacity goBack={()=>this.backAction} onPress={()=>this.homepage()}>
              <Image key={item.image_path} 
                source={require('./assets/images/'+{item.image_path})}
            </TouchableOpacity> 
</View>
)
}

require doesn't work dynamically like that. Since you already have the images in the assets, you should write the require's for each of them in advance and call the appropriate one when needed. You can read more about this limitation here.

Related

how to display the url of a picture of an item from my sql database in react native?

i'm trying to display the picture of a shop in a single-shop page after clicking on said shop on the shop-list page.
once i clicked it takes the datas (from phpmyadmin) of that shop only and display the details. the name, adresse, phone number, etc all work but the picture.
i created a colomn image where i stock the url that leads to the picture located in my assets folder of the react folder.
but i tried just with url to see if the Image balise would work... AND IT WORKED :
<View><Image style={{resizeMode : 'cover'}} source= {require('../../../assets/picture1.jepg')} /></View>
so i then tried with an object called pharmaimages (it's basically just the url itself that i stocked in my database with the '' included) but it says invalid. i also tried with the propriety uri but it's even less clear.
<View><Image style={{resizeMode : 'cover'}} source= {require(pharmaimages)} /></View>
in my mind it makes perfect sense but it just doesn't work
Try storing it as require('../../../assets/image.jpeg') in the database. Fetch the data and then once you map it or whatever you do in your app, show it using the following code:
<View>
<Image style={{resizeMode : 'cover'}} source={image} />
</View>
This is one of the common issues, that most of developers got into.
The other answers may also right, But to be more precise I am adding my comments on this Question.
Actually, the require statement will never evaluate value we are passing as parameter, It will directly look for the path we are providing into it, also It is working in same way like we are importing other libraries or Components.
So if we provide dynamic value at run time with require we may fail to see expected behaviour.
Here, I am also attaching some important links which might help you to understand clearly.
Links:
React Native Official Image Doc
Same issue related thread on Stackoverflow
WORKAROUND
To go with workaround for this kind of situation you can directly store your file paths with require function in your data storage.
for ex.
Instead of storing path like '../../../abc/def.png'
Store value as require('../../../abc/def.png')

Dynamic background images not loading

I'm using Vue 3 along with Tailwind and in my template I display a list of background images, so I'm looping through an array of images and this div is responsible for showing them:
<div :class="`h-full bg-[url('#/assets/img/${article.preview_image}')] bg-center bg-no-repeat bg-cover hover:scale-105 transition duration-[2000ms] ease-in-out`" />
This way it doesn't work although I have no errors in the console and when I check the DOM it's rendered alright, the images just don't show up
The weird part is that when I hard code the name of the image like bg-[url('#/assets/img/my_image.jpg')] it works, and when I go back to using my loop variable it still works although it was not working at first, and it's not cache related because I disabled it
And then when I restart the server the images are gone again
Any idea what's causing this?
By the way, the data comes from a data.json file, if it matters. Like:
[
{ preview_image: 'xxx.jpg'},
{ preview_image: 'xxx.jpg'}
{ preview_image: 'xxx.jpg'}
]
I tried to use a .ts file instead but the problem remains
This may be a webpack issue where your image files are not bundled correctly. I se you have tried a .ts file. Can you try again but use require("filePath"), with the image files. This ensures that the files are bundled.
Cheers :)

Cannot read image file in appcelerator titanium

I have an image stored at /assets in my project folder and I am trying to read it using Ti.Filesystem.getFile(). The code prints the blob data in android but it prints undefined in iOS.
Following function is called on Button click event https://pastebin.com/QgqLQPyz
function readImg(e) {
var localPath = '/butterfly.jpg';
var cachedFilename = Ti.Utils.sha1(localPath) + localPath.substr(localPath.lastIndexOf('.'));
console.log("cachedFilename:---"+cachedFilename);
var cachedFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationCacheDirectory, cachedFilename);
if(!cachedFile.exists()){
var blob = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, localPath).read();
console.log("-----------blob in not exists:"+JSON.stringify(blob));
}
}
When the same image path is set in ImageView it gets displayed so the issue is not with path . What am I missing here ? pls help. Thank you.
The best option so you don't have to do anything specific to the images at all (keep in mind, image manipulation is pretty heavy to do on runtime), is to use a module that was made for this purpose, av.imageview. This allows you to configure all kinds of content modes.
An option to get your code to work is to get the blob using the the getAsset method.
var blob = Ti.Filesystem.getAsset('/images/butterfly.jpg');
and then resize where you see fit. But I would advise you, if you do need to do this every time the app runs, then just resize once and store that resized image to be used after that. That way there will only be a single time the image needs resizing.

AWS SDK PHP version 2 - retrieving image dimensions?

Is it possible to retrieve the dimensions of an image stored on Amazon S3?
If the answer is no, are there any other ways around it other than downloading the image to my server to which sounds inefficient?
I'm using version 2 of the AWS SDK for PHP.
I've been looking through what is returned from the following code but doesn't seem to give dimensions.
$result = $s3->getObject(array(
'Bucket' => 'BUCKET_NAME',
'Key' => 'KEY_NAME'
));
var_dump($result);
I'm not 100% familiar with SDK2. With 1.5 you could do this
getimagesize($s3->get_object_url($bucket,$filename));
I think this is still possible as long as you can access publicly the image (or you have to find your way around authorized urls)
Obviously, your php must be enabled to open remote files.
I agree with the db cache. I run every image filename through a class that checks mysql for a match. If it finds one, it returns width, height and a preformatted sizetag ready to go. If the image and size are not found, it uses getimagesize() to return the same info, which it stores for next time. I also built in a resize method should I want to cheat a bit and resize the sizetag (but not the file) proportionally on the fly.
I don't know if storing the info is faster than getimagesize() as it downloads. S3 is pretty fast.
Due to lack of response I'll presume it's not possible... Didn't r3ally want to do it with JavaScript but this is how I did it.
<img src="image.jpg" id="image" />
<script>
// This runs after the image has loaded
$('#image').load(function() {
// Use the below code to get the height and width
// document.getElementById('image').width
// document.getElementById('image').height
});
</script>

How do you assign a default Image to the Blob object in Play framework?

I followed this nice article
http://www.lunatech-research.com/playframework-file-upload-blob
and have a perfectly working image upload solution
My questions is, if the user doesn't select any image, how do I assign a default image during save (probably stored in the server)?
if (!user.photo)
user.photo= ?;
user.save();
The one-hack that I can think of is upload the default image and see which UID "Play" stores in the /tmp directory and assign that above. Is there an elegant named* solution to this?
when I say named, I mean I want the code to look like (which means I know what I'm doing and I can also write elegant automated code if there are more than one picture)
user.photo= "images/default/male.jpg"
rather than (which means I'm just hacking and I can't extend it elegantly for a list of pictures)
user.photo= "c0109891-8c9f-4b8e-a533-62341e713a21"
Thanks in advance
The approach I have always taken is to not change the model for empty images, but instead do something in the view to show a default image, if the image does not exist. This I think is a better approach because your are corrupting your model for display purposes, which is bad practice (as you may want to be able to see all those who have not selected an image, for example).
To achieve this, in your view you can simply use the exists() method on the Blob field. The code would look like
#{if user.photo.exists()}
<img src="#{userPhoto(user.id)}">
#{/if}
#{else}
<img src="#{'public/images/defaultUserImage.jpg'}">
#{/else}
I have assumed in the above code that you are rendering the image using the action userPhoto as described in the Lunatech article.
I'd assume you can store the default image somewhere in your applications source folder and use
user.photo.set(new FileInputStream(photo), MimeTypes.getContentType(photo.getName()));
to save the data. Photo is just a File object, so you can get the reference of your default image and use it.