I have created a js file where an array contains multiple objects. Every object has an image path given. Using for loop, I am importing every object to my component. Everything works fine except the image. It's broken. It's not taking the relative path. I have stored all the images in a folder. Below is my code:
Data.js
export const dashboardUtil = [
{
title: "Posts",
count: 500,
image: "/src/images/1.png"
}
//rest of the objects
]
Component.js
let blocks = [];
for(let i=0;i<dashboardUtil.length;i++){
blocks.push(
<Col xs={12} md={6} sm={6}>
<div className="main-block" className="stats-block">
<h3>{dashboardUtil[i].title}</h3>
<p>{dashboardUtil[i].count}</p>
<img src={dashboardUtil[i].image} />
</div>
</Col>
);
}
image: "/src/images/1.png"
This is not a relative path, its absolute (starts with slash). If you intend it to be relative, use ./ e.g. ./src/images/1.png.
The bigger issue is that you're providing a path to a local resource to the context of the users browser. It expects this to be a http(s):// resource. You need to provide an endpoint that your web server handles and serves up the resource.
Either:
Your image needs to go into a location your web server can access, and you need to set the img src attribute to reference that location
You should look into webpack and a file loader plugin that takes a local image path via require(), and copies that to an accessible location.
use :
import image from "../pathToImageFolder/image1.png";
//path to image will be automatically constructed by webpack
<img src={image}>
Related
I have been using Svelte for a little while and now I have switched to SvelteKit so I can add multiple pages. I want to add some images to my site but I don't know where to put them. In Svelte I would just put them in public/images but there is no public folder with SvelteKit (I set it up with npm init svelte#next my-app if that matters). Would I put them in static?
Thanks!
I added the images in static/images and referenced them with src="/images/photo.jpg" like #b2m9 said and it works perfectly.
I recommend putting images under src/lib, not static. For example you could make a src/lib/images or src/lib/assets folder and put them there.
The reason is performance:
For files imported from anywhere under src, at compile time Vite adds a hash to the filename. myImage.png might end up as myImage-a89cfcb3.png. The hash is based on the image contents. So if you change the image, it gets a new hash. This enables the server to send a very long cache expiration to the browser, so the browser can cache it forever or until it changes. It's key-based cache expiration, which IMO is the best kind: cached exactly as long as it needs to be. (Whether the server actually sends the right caching headers in the response may depend on which SvelteKit adapter you use and what host you're on.)
By contrast, images under static don't have a hash added to their name. You can use the static directory for things like robots.txt that need to have a specific filename. Since the filename stays unchanged even if its contents change these files by necessity end up having a cache-control value that includes max-age=0, must-revalidate and an etag, which means even if the browser caches the image it still has to make a server round-trip to validate that the cached image is correct. This slows down every image on your site.
Usage:
When putting images under src/lib, you reference them like this:
<script>
import img from '$lib/images/img.png';
</script>
<img src={img} alt="Image" />
I recommend simplifying by adding svelte-preprocess-import-assets to your project, which automates the process of importing images and cleans up your code. You wrote the following and it generates the code above:
<img src="$lib/images/img.png" alt="Image" />
As Sveltekit uses Vitejs, there is a easy solution mentioned in Vitejs official web site (Click Here).
First inside the script tag :
<script>
const imgUrl = new URL('./img.png', import.meta.url).href
</script>
then inside your Image tag just use that variable,
<img src="{imgUrl}" alt="" />
or,
<div class=" h-screen w-full" style="background-image: url('{bgUrl}') ;">
</div>
You can import static images from any relative path.
there is also svelte-image.
"Svelte image is a pre-processor which automates image optimization using sharp.
It parses your img tags, optimizes or inlines them and replaces src accordingly. (External images are not optimized.)
Image component enables lazyloading and serving multiple sizes via srcset.
This package is heavily inspired by gatsby image.
Kudos to #jkdoshi for great video tutorial to Svelte Image."
-https://github.com/matyunya/svelte-image
As a back-end for vue.js I use laravel (port 8000)
In my db I have the user and the name of it's profile photo (this.user.photo).
So, I want to show this photo.
<img :src="require(`http://localhost:8000/images/${this.user.photo}`)" alt="Profile Photo">
When I go to http://localhost:8000/images/1.png I actually see the image, but the Vue says:
Module not found: Error: Can't resolve 'http://localhost:8000'
PS: console.log(this.user.photo) outputs 1.png
UPD: I've seen many solutions, like this or this, but they do not work
Looks like your images are already hosted on the server and you are not bundling them during build. In this case, you need not use require and directly refer to your images in the template as
<img :src="'http://localhost:8000/images/' + user.photo" alt="Profile Photo">
Remember that require is a method provided by webpack to resolve your dependancy URLs during build such that you need not worry about the absolute URLs. require helps us refer to URLs relative to the modules which are resolved by webpack during build.
In short, use require when you have static assets inside your Vue project module
You can call the image directly with path if the image is not in public path
<img :src=`../../images/${user.photo}` alt="Profile Photo">
This will build image in the path where the compiling the JS and the image public path will automatically added.
If you're trying to add image from public path, you can initialise the origin path in the data section and call the image like follows
data:()=>{
return {
path: document.location.origin
}
}
<img :src=`${path}/images/${user.photo}` alt="Profile Photo">
Note: you don't need to use this in the template section.
You should use require and point to the image.
Make sure that the path is relative to the module that uses it.
Write a function to return the image URL
var app = new Vue({
el: '#app',
methods: {
getPicture() {
return 'https://vuejs.org/images/logo.png'
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<img :src="getPicture()" alt="Profile Photo">
</div>
I am trying to load images from the public folder in the vue components. The asset helper doesn't work in vue , so I need to use the format
<img :src="'img/ic_add-sm.svg'" >
But instead of looking for the images in the public folder , vue is appending the current URL to the image path. For example , if the url is www.example.com/posts
it adds www.example.com/posts/img/ic_add-sm.svg
instead of www.example.com/img/ic_add-sm.svg
Add a forward slash to the beginning of your image path.
<img :src="'/img/ic_add-sm.svg'">
Since you don't appear to be doing anything special you should be able to just use
<img src="/img/ic_add-sm.svg">
At first bind the value of image source
<img :src="getPhoto() + variableName" />
Then create the function under your methods section and simply return the directory location, that's all.
getPhoto(){
return 'images/';
}
Note that, You cant declare directory location directly to :src attribute.
I have installed React using create-react-app. It installed fine, but I am trying to load an image in one of my components (Header.js, file path: src/components/common/Header.js) but it's not loading. Here is my code:
import React from 'react';
export default () => {
var logo1 = (
<img
//src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-goose.jpg"
src={'/src/images/logo.png'}
alt="Canvas Logo"
/>
);
return (
<div id="header-wrap">
<div className="container clearfix">
<div id="primary-menu-trigger">
<i className="icon-reorder"></i>
</div>
<div id="logo">
<a href="/" className="standard-logo" data-dark-logo='/images/logo-dark.png'>{logo1}</a>
<a href="/" className="retina-logo" data-dark-logo='/images/logo-dark#2x.png'>
<img src='/var/www/html/react-demo/src/images/logo#2x.png' alt="Canvas Logo" />
</a>
</div>
</div>
</div>
);
}
If I write the image path as src={require('./src/images/logo.png')} in my logo1 variable, it gives the error:
Failed to compile.
Error in ./src/Components/common/Header.js
Module not found: ./src/images/logo.png in /var/www/html/wistful/src/Components/common
Please help me solve this. Let me know what I am doing wrong here.
If you have questions about creating React App I encourage you to read its User Guide.
It answers this and many other questions you may have.
Specifically, to include a local image you have two options:
Use imports:
// Assuming logo.png is in the same folder as JS file
import logo from './logo.png';
// ...later
<img src={logo} alt="logo" />
This approach is great because all assets are handled by the build system and will get filenames with hashes in the production build. You’ll also get an error if the file is moved or deleted.
The downside is it can get cumbersome if you have hundreds of images because you can’t have arbitrary import paths.
Use the public folder:
// Assuming logo.png is in public/ folder of your project
<img src={process.env.PUBLIC_URL + '/logo.png'} alt="logo" />
This approach is generally not recommended, but it is great if you have hundreds of images and importing them one by one is too much hassle. The downside is that you have to think about cache busting and watch out for moved or deleted files yourself.
If you want load image with a local relative URL as you are doing. React project has a default public folder. You should put your images folder inside. It will work.
In React or any Javascript modules that internally use Webpack, if the src attribute value of img is given as a path in string format as given below
e.g. <img src={'/src/images/logo.png'} /> or <img src='/src/images/logo.png' />
then during build, the final HTML page built contains src='/src/images/logo.png'. This path is not read during build time, but is read during rendering in browser. At the rendering time, if the logo.png is not found in the /src/images directory, then the image would not render. If you open the console in browser, you can see the 404 error for the image. I believe you meant to use ./src directory instead of /src directory. In that case, the development directory ./src is not available to the browser. When the page is loaded in browser only the files in the 'public' directory are available to the browser. So, the relative path ./src is assumed to be public/src directory and if the logo.png is not found in public/src/images/ directory, it would not render the image.
So, the solution for this problem is either to put your image in the public directory and reference the relative path from public directory or use import or require keywords in React or any Javascript module to inform the Webpack to read this path during build phase and include the image in the final build output. The details of both these methods has been elaborated by Dan Abramov in his answer, please refer to it or use the link: https://create-react-app.dev/docs/adding-images-fonts-and-files/
There are lot of good answers here and more expert opinions than myself. But I will just share my experience and what worked for me.
I was irritated by the fact that there is so much go around just to have a simple inclusion of images. Hence here is what I did-
Create a seperate component (file) myimages.jsx
import image1 from "../img/someimage.png";
import image2 from "../img/otherimage.png";
const ImageData=[image1,image2,image3]
export default ImageData;
I then just imported this ImageData component in the file (component) I as using the images. This way I turned a cpmponent into a 'folder' to get all my images.
Like I said, not an expert but this resolved my frustration with lack of importing images quickly in React.
You have diferent ways to achieve this, here is an example:
import myimage from './...' // wherever is it.
in your img tag just put this into src:
<img src={myimage}...>
You can also check official docs here: https://facebook.github.io/react-native/docs/image.html
In order to load local images to your React.js application, you need to add require parameter in media sections like or Image tags, as below:
image={require('./../uploads/temp.jpg')}
In React.js latest version v17.0.1,
we can not require the local image we have to import it.
like we use to do before = require('../../src/Assets/images/fruits.png');
Now we have to import it like =
import fruits from '../../src/Assets/images/fruits.png';
Before React V17.0.1 we can use require(../) and it is working fine.
Instead of use img src="", try to create a div and set background-image as the image you want.
Right now it's working for me.
example:
App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div>
<div className="myImage"> </div>
</div>
);
}
}
export default App;
App.css
.myImage {
width: 60px;
height: 60px;
background-image: url("./icons/add-circle.png");
background-repeat: no-repeat;
background-size: 100%;
}
Best approach is to import image in js file and use it. Adding images in public folder have some downside:
Files inside public folder not get minified or post-processed,
You can't use hashed name (need to set in webpack config) for images , if you do then you have to change names again and again,
Can't find files at runtime (compilation), result in 404 error at client side.
First, you need to create a folder in src directory then put images you want.
Create a folder structure like
src->images->linechart.png
then import these images in JSX file
import linechart from './../../images/linechart.png';
then you need use in images src like below.
<img src={linechart} alt="piechart" height="400px" width="400px"></img>
We don't need base64, just give your image path and dimensions as shown below.
import Logo from './Logo.png' //local path
var doc = new jsPDF("p", "mm", "a4");
var img = new Image();
img.src = Logo;
doc.addImage(img, 'png', 10, 78, 12, 15)
I've learned and implement successfully that how to upload images on server disk with servlet from Here and now trying to show the image on another jsp userProfile.jsp with the help of following code :
<img src="<jsp:include page='WEB-INF/jspf/profileImage.jspf' />" height="175" width="175" />
and code of profileImage.jspf is as follows:
OutputStream o = response.getOutputStream();
InputStream is = new FileInputStream(new File("../files/backPetals.jpg"));
byte[] buf = new byte[32 * 1024];
int nRead = 0;
while( (nRead=is.read(buf)) != -1 ) {
o.write(buf, 0, nRead);
}
o.flush();
o.close();
return;
but it does not works..
Any other ways to display the image from disk on jsp together with other matter on page?
I've saved my images on /files directories on the application root folder.
There are several serious mistakes in the approach:
You should not store the uploaded file in the application root folder. They will all get lost whenever you redeploy the WAR (simply because those files are not contained in the original WAR file.
The <img src> should not contain the raw image content, but it should contain an URL which returns the file content. E.g.
<img src="profilePictures/${user.profilePictureFilename}" />
You should not use JSP to write binary data to the response. Use a servlet instead. Or if you can, just add the path to uploaded files as another webapp context.
Here are several answers which should help you in the right direction:
How to provide relative path in File class to upload any file?
What is the correct path I need to see my uploaded image?
How I save and retrieve an image on my server in a java webapp
The syntax of an img tag is <img src="url_of_the_image" .../>. What you're doing is <img src="contents_of_the_image_file" .../>.
You need to generate a URL to a servlet, and this servlet needs to open the image file and send its content to the output stream. You can't download an HTML file and an image in a single HTTP request.