Vue img src path does not work the same as :src - image

I use Vue. I try to output an image and it works fine when I use src but not when I use :src.
Works
<img src="../assets/image.png" />
Does not work
<img :src="`../assets/${image}.png`" />
What I've tried, but did not work
# first in the path.
~ first in the path.
./ first in the path.
/ first in the path.
require but it throws an error if the image can't load. I prefer the native broken image icon, which does not break the script.
My output
The variable image contains the filename which in this case would be image.
The output from both version is like below:
<img src="../assets/image.png" data-v-469af010=""> <!-- src -->
<img src="/img/image.f556f8c5.png" data-v-469af010=""> <!-- :src -->
For some reason they differ quite alot.
How can I solve it?

I solved this problem with this:
<img :src="cover(url)" /> // I call a method cover.
// Method cover
cover(url) {
if (url !== ''){ // You can check any matching expression.
try {
url = require('#/assets/img/' + url)
} catch (e) {
url = require('#/assets/img/default.jpg'); // I used a default image.
}
}
else
url = require('#/assets/img/default.jpg'); // Default image.
return url;
}

Bind src to the method.
getImgUrl(image) {
return `../assets/${image}.png`
}
in HTML
<img :src="getImgUrl(image)" />

If image variable is name of file
<img :src="'../assets/'+image" />
You should not use $ in template.

Related

Passing and binding img src from props in Vue.js

I am trying to display an image with the img tag by using a path from props for the src attribute.
I've tried changing the path with #, using the whole path with src, adding ../assets/ in the component and only passing the file name (orange.png) as props.
I always get the default broken image displayed.
When inspecting in the browser, the path seems fine.
When I display the image directly, I can see that the path is resolved to some different path <img data-v-1212d7a4="" src="/img/orange.7b71a54c.png">.
Edit:
Additionally I tried this post Can't dynamically pass relative src path for imgs in Vue.js + webpack ,
where using <img :src="require(picture_src)" /> is given as an answer.
This leads to an error: Error in render: "Error: Cannot find module '../assets/orange.png'"
(Edit2:
This answer in the end worked for me in the end as described in my answer post.)
The same error occurs with the similar webpack method using let images = require.context('../assets/', false, /\.png$/) in my script part, as the answer on this post Can't dynamically pass relative src path for imgs in Vue.js + webpack .
I am new to Vue.js, so I don't exactly know what is happening or how to search for this or it might not have anything to do with what I'm originally trying.
I am able to display my image when I pass the path directly, like this
<img src="../assets/orange.png"/>
Now I'd actually like to pass it to my component in the props and then, inside the component, display it reading the path from props.
Component
<template>
<div>
<img :src=picture_src />
<div class="pic_sub">{{pic_desc}}</div>
</div>
</template>
<script>
export default {
name: 'PictureCard',
props: {
picture_src: String,
pic_desc: String
}
}
</script>
Using the component:
<template>
<div>
<PictureCard pic_desc='some description text' picture_src='../assets/orange.png' />
</div>
</template>
<script>
import PictureCard from './components/PictureCard.vue'
export default {
name: 'app',
components: {
PictureCard
}
}
</script>
If it is possible, I'd love to display my from a path that is passed through the component's props.
Otherwise I'd love to know some other solutions, work-arounds or knowledge on best practices in this case.
This worked for me
<img :src="require(`#/assets/img/${filename}`)">
where filename is passed in as a String prop e.g. "myImage.png".
Make sure you use the path specific to your project.
Source: https://github.com/vuejs-templates/webpack/issues/450
Note: # is a webpack alias for /src that is set by default in Vue projects
After some research, I understand that my problem has to do with webpack and resolving filepaths. I used a modified version from this answer:
Vue.js dynamic images not working
and this answer:
Can't dynamically pass relative src path for imgs in Vue.js + webpack
Since the link in the second answer was dead, here's an active link to require.context documentation:
https://webpack.js.org/guides/dependency-management/#requirecontext
My mistake when trying the second link's answer was that I returned only orange.png as the path, while I needed to add ./ at the beginning.
My working picture component now looks like this.
<template>
<div>
<img :src="resolve_img_url(picture_src)" />
<div class="pic_sub">{{pic_desc}}</div>
</div>
</template>
<script>
export default {
name: 'PictureCard',
props: {
picture_src: String,
pic_desc: String
},
methods: {
resolve_img_url: function (path) {
let images = require.context('../assets/', false, /\.png$|\.jpg$/)
return images("./"+path)
}
}
}
</script>
I edited the regular expression to match .png and .jpg file endings. Therefore passing the prop looks like this now
<PictureCard picture_src='orange.png' pic_desc='some picture description'/>
This works for me:
This is how i use my Componenent.
<image-element
:imageSource="require('#/assets/images/logo.svg')">
</image-element>
My Image Component:
<template>
<div>
...
<img v-bind:src=imageSource />
...
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import { Component, Prop } from 'nuxt-property-decorator'
#Component({
components: {
.....
}
})
export default class extends Vue {
...
#Prop({ default: '' }) imageSource!: String
...
}
</script>
Newer solution:
The 'require()'-method does not work when using Vite.
I got this error: ReferenceError: require is not defined.
This is how I solved it without 'require()' and with composition API:
From parent component:
<ChildComponent icon-filename="icon.svg" />
ChildComponent:
<template>
<div>
<img :src="getImageUrl()">
</div>
</template>
<script setup lang="ts">
import {defineProps} from "vue";
const props = defineProps({
iconFilename: String
})
function getImageUrl() {
// This path must be correct for your file
return new URL(`../assets/icons/${props.iconFilename}`, import.meta.url)
}
</script>
this is my favorite super simple way to do it. It can easily be reused in any file in any folder in my project. Just pass the actual path as a string from the perspective of the parent:
//some file
<ParentA>
<ImageComponent
myImagePath="../../../../../myCat.png"
/>
</ParentA>
//some other file in a different folder in my project
<ParentB>
<ImageComponent
myImagePath="../../myCat.png"
/>
</ParentB>
//child component file
<template functional>
<div>
<img :src="props.myImagePath">
</div>
</template
Thats all not working for me :D
The template File is wrong!
you need to add ":" before you set your prop.
thats how i should use the PictureCard
<PictureCard :picture_src="require('orange.png')"
pic_desc='some picture description'/>
and thats how my PictureCard should look like:
<template>
<div>
<img v-bind:src="picture_src" />
</div>
</template>
export default class PictureCard extends Vue {
#Prop({ default: require("#/assets/orange.svg") }) img!: string
}
so in case no prop is setted, so i added a default prop too.
and yes i only used the image.

how to Import an image in React with parcel-bundle

I want to add an image with a require statement.
But I got the following error:
Cannot find module '../../../assets/skillName.png'
I build app using parcel-bundle and I don't use webpack.
The path to the image is correct, because if I use a static link, it works well:
<img src={require(`../../../assets/skillName.png`)}/>
Try doing it this way:
{Object.keys(this.props.skillset).map((skill) => {
let source = require(`../../../assets/${skill}.png`);
return (
<div key={skill}>
<img src={source}/>
</div>
)
})}
https://codepen.io/smilesaayush/pen/oyzMZd
I did it this way and it worked for me, try not using require, and give absolute url in image source, which I think in your case should be - window.location.host + relative url.
class App extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
{[100, 200].map((len) => {
return (
<div key={len}>
<img src={`https://placeimg.com/${len}/${len}/any`}/>
</div>
)}
)}
</div>
)
}
}
you can control the steps:
1.really skillName.png image place the assets folder.
2.You can remove skillName name from json data.then see other images.if you can show other image, your image name is incorrect.
because your code is correct but can be small problem.

Display image in laravel

I have already uploaded the image in a folder and stored its path in the database field. I am trying to display image like this:
Controller:
public function showProfileImage($id)
{
$profileimage = UserProfileModel::where(['usrID' => $id])->first();
return view('userlogin::welcome')->with('profileimage', $profileimage->userPicpath);
}
my blade template has:
<img src="{{ route('showprofileimage', ['id' => Session::get('loggedinuserid')]) }}" height="150" />
But the path returned in the src is the route path, it doesn't contain the 'profileimage' path returned form the controller. How do i do this? Thanks
The route('<named route>') helper function returns the URL to a page/endpoint/resource that was defined as:
Route::get('some/uri', ['as' => 'showprofileimage', function() {
//
});
It may not be used for displaying images (although it could be used with a few tweaks), but I would go with either one of the following approaches:
If you have the fully qualified image URL then you can use the url() helper function. Do:
<img src="{{ url('showprofileimage') }}" ... />
If your image is in the /public directory, you can use the asset() helper function:
<img src="{{ asset('path/to/profile/image') }}" ... />
If your image is in the /storage directory, you can use the storage() helper function (but I believe this is not recommended):
<img src="{{ storage('path/to/profile/image') }}" ... />
Hope this helps. Cheers!

Display image in a View, file is not found

I want display image in my View. But file isn't found, file exist.
string file = Server.MapPath("~") + #"/App_Data/Plakaty/" + wyd.WydarzenieId.ToString() + ".jpg";
ViewBag.file_exist = System.IO.File.Exists(file);
I try: (Is display only alt:)
#if (ViewBag.file_exist == true) // it's TRUE
{
<img src="../../App_Data/Plakaty/1029.jpg" alt="p" />
<img src="~/App_Data/Plakaty/1029.jpg" alt="p1" />
<img src="#Url.Content("~/App_Data/Plakaty/1029.jpg")" alt="image"/>
<img src="#Url.Content("../../App_Data/Plakaty/1029.jpg")" alt="image2"/>
}
<img src="../../App_Data/Plakaty/1029.jpg" alt="p" />
Taking this as example, is App_Data really in the path for the image to the outside world? Sometimes internal paths are different.

Cannot display an image from filesystem in grails

I'm new to grails (1.3.7) and I've been put in a strange situation with displaying an image from the filesystem. The one.png picture is put into web-app/images/fotos directory. The zz.gsp:
<img src="${resource(dir:'images/fotos', file:'one.png')}" alt="Nothing" />
related to the void action def zz = {} works fine. But if I intend to display the same picture in rawRenderImage.gsp:
<body>
<p>
${fdir} <br/> ${fname} <!-- OK -->
</p>
<g:if test="${fname}">
<img src="${resource(dir:'fdir',file: 'fname')}" alt ="Nothing"/>
</g:if>
</body>
the picture doesn't appear inspite of the parameters fdir and fname pass to the page. The action in the controller is:
def rawRenderImage = {
// def basePath = servletContext.getRealPath("/")
// def basePath = grailsAttributes.getApplicationContext().getResource("/").getFile().toString() + "/images/fotos/"
// def basePath = grailsAttributes.getApplicationContext().getResource("/").getFile().toString()
// def fname = params.photoId + ".png"
// def fname = "/images/fotos/" + params.photoId + ".png"
basePath = "images/fotos" // or basePath=”images” for /images/one.png
fname=”one.png”
[fdir:basePath, fname:fname]
}
Even direct assigns basePath=”images/fotos” and fname=”one.png” don't work, as well as any combinations with basePath to obtain the absolute path. Even the case when I put the picture in images directory doesn't work. I use netbeans, but it also doesn't work in console mode.
Help please.
When passing in your filename and directory as variables in the model, don't quote them in your tag's src attribute. Then the Groovy ${} evaluation will evaluate to the variables and not as Strings.
<g:if test="${fname}">
<img src="${resource(dir:fdir,file:fname)}" alt ="Something"/>
</g:if>

Resources