Displaying images, which are stored in a string, on a JSP - javascript

I am using the below mentioned code on my JSP:
<%
List eCCategoryList = form.getCategoryList();
//Map<String, String> catNameImgMap = (Map<String, String>) session.getAttribute("catNameImgMap");
Map catNameImgMap = (Map) form.getBlogIdNameMap();
String strImage = "";
Iterator it = eCCategoryList.iterator();
ECircularCategory category = null;
int counter = 0;
while (it.hasNext()) {
category = (ECircularCategory) it.next();
strImage = (String) catNameImgMap.get(category.getName());
%>
strImage contains image which I need to display on my JSP. I tried displaying the images like:
<img src="<%=strImage%>" alt="Test Image 1" width="270" height="190"/>
but the above code is not working a simple blank space is shown and nothing else, I need to display the images on my JSP page each of which are stored in the strImage string, how do I do it?
Please suggest.

You could use JSTL tag:
<img src="<c:url value="<%=strImage%>"/> alt="Test Image 1" width="270" height="190"/>
Here is a good link about JSTL.
Hope it helps...

Related

how to display byte[] as picture in html with java

I use spring mvc and JPA in my project. I get file as byte[] and save in Database. but when I want to display in <img tag of html it don't display.
my entity is:
class Photo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
#Lob
private byte[] profilePic;
// getter and setter
}
value in Database is:
but my server response is:
{
"id": 4,
"title": "pic 1",
"profilePic": "ZGF0YTppb...VFtQ0M=",
}
and display in html:
<img src='ZGF0YTppb...VFtQ0M=' />
//or
<img src='data:image/jpeg;base64,ZGF0YTppb...VFtQ0M=' />
What to do to display the photo?
thanks
Assuming it's base64 encoded:
<img src='data:image/jpeg;base64,ZGF0YTppb...VFtQ0M=' />
Basically you can use data urls with this format depending on what content [type] you want to display:
data:[<mime type>][;charset=<charset>][;base64],<encoded data>
HTML:
<img id="profileImg" src="">
JS:
document.getElementById("profileImg").src = "data:image/png;base64," + profilePic;
This assumes that your image is stored in PNG format (and base64 encoded). For other image format (JPEG, etc.), you need to change the MIME type ("image/..." part) in the URL.

How to display multiple images in a html div, using javascript's array and loop

I want to display multiple images in an HTML <div>, so that user can select select the 'avatar' for their profile. I have written this javascript, but it displays only last image in array.
const array1 =[
"Multiavatar1.png",
"Multiavatar2.png", "Multiavatar3.png", "Multiavatar4.png", "Multiavatar5.png", "Multiavatar6.png", "Multiavatar7.png", "Multiavatar8.png", "Multiavatar9.png", "Multiavatar10.png", "Multiavatar11.png", "Multiavatar12.png", "Multiavatar13.png", "Multiavatar14.png", "Multiavatar15.png", "Multiavatar16.png", "Multiavatar17.png", "Multiavatar18.png", "Multiavatar19.png", "Multiavatar20.png", "Multiavatar21.png", "Multiavatar22.png", "Multiavatar23.png", "Multiavatar24.png", "Multiavatar25.png", "Multiavatar26.png", "Multiavatar27.png", "Multiavatar28.png", "Multiavatar29.png", "Multiavatar30.png", "Multiavatar31.png", "Multiavatar32.png", "Multiavatar33.png", "Multiavatar34.png", "Multiavatar35.png", "Multiavatar36.png", "Multiavatar37.png", "Multiavatar38.png", "Multiavatar39.png", "Multiavatar40.png", "Multiavatar41.png", "Multiavatar42.png",
];
array1.forEach( element => {
var image = `<img src="avatar/${element}" alt="img">`;
document.getElementById('avatar_div').innerHTML = image;
});
But apparently I tried using the below script in a separate file, and this worked.
const array1 =[ "Multiavatar1.png",
"Multiavatar2.png",
"Multiavatar3.png",
"Multiavatar4.png", "Multiavatar5.png", "Multiavatar6.png", "Multiavatar7.png", "Multiavatar8.png", "Multiavatar9.png", "Multiavatar10.png", "Multiavatar11.png", "Multiavatar12.png", "Multiavatar13.png", "Multiavatar14.png", "Multiavatar15.png", "Multiavatar16.png", "Multiavatar17.png", "Multiavatar18.png", "Multiavatar19.png", "Multiavatar20.png", "Multiavatar21.png", "Multiavatar22.png", "Multiavatar23.png", "Multiavatar24.png", "Multiavatar25.png", "Multiavatar26.png", "Multiavatar27.png", "Multiavatar28.png", "Multiavatar29.png", "Multiavatar30.png", "Multiavatar31.png", "Multiavatar32.png", "Multiavatar33.png", "Multiavatar34.png", "Multiavatar35.png", "Multiavatar36.png", "Multiavatar37.png", "Multiavatar38.png", "Multiavatar39.png", "Multiavatar40.png", "Multiavatar41.png", "Multiavatar42.png",
];
array1.forEach( element => {
var h = `<img src="avatar/${element}" alt="img"><br>`;
document.write(h);
});
Can anyone explain me, what am
I doing wrong in first script.
And suggestions for my code to work?
Your first sample is not working because you are overwriting the previous HTML.
Your second sample is working because document.write appends the HTML.
To make the first sample work, use += (addition assignment operator) instead of =:
const array1 = [
"Multiavatar1.png",
"Multiavatar2.png", "Multiavatar3.png", "Multiavatar4.png", "Multiavatar5.png", "Multiavatar6.png", "Multiavatar7.png", "Multiavatar8.png", "Multiavatar9.png", "Multiavatar10.png", "Multiavatar11.png", "Multiavatar12.png", "Multiavatar13.png", "Multiavatar14.png", "Multiavatar15.png", "Multiavatar16.png", "Multiavatar17.png", "Multiavatar18.png", "Multiavatar19.png", "Multiavatar20.png", "Multiavatar21.png", "Multiavatar22.png", "Multiavatar23.png", "Multiavatar24.png", "Multiavatar25.png", "Multiavatar26.png", "Multiavatar27.png", "Multiavatar28.png", "Multiavatar29.png", "Multiavatar30.png", "Multiavatar31.png", "Multiavatar32.png", "Multiavatar33.png", "Multiavatar34.png", "Multiavatar35.png", "Multiavatar36.png", "Multiavatar37.png", "Multiavatar38.png", "Multiavatar39.png", "Multiavatar40.png", "Multiavatar41.png", "Multiavatar42.png",
];
array1.forEach(element => {
var image = `<img src="avatar/${element}" alt="img">`;
document.getElementById('avatar_div').innerHTML += image;
});
Demo:
const array1 = [
"https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1",
"https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1"
];
array1.forEach(element => {
var image = ` <img src = "${element}" alt = "img">`;
document.getElementById('avatar_div').innerHTML += image;
});
``
<div id="avatar_div"></div>

dynamic Backgrounds for django using image upload

I've looked around and haven't found a satisfactory solution. I am trying to uploaded an image via the Django admin interface using models and then call that uploaded image to be used as the background for a div .i.e - I create football called Salford City, I upload a picture of the team. I will have several teams. If I choose Salford then the background changes, if I choose Brighton Albion then the background changes. I have it working using javascript and hard coded cities but I would like to be able to do it dynamically without have to change base coding to enable easy scaling. Current code is as follows:
Models.py:
class City(models.Model):
index = models.CharField(unique=True, max_length=250, null=False, blank = False, verbose_name = 'City Inner Search Name(lowercase)')
landing_page_description = models.CharField(max_length=5000, null=True, blank = True, verbose_name = 'City Description')
name = models.CharField(max_length=250, null=False, blank = False, verbose_name = 'City Common Name')
country = models.ForeignKey(Country, null=True, blank=True)
image = models.ImageField(upload_to="images/", blank=True, null=True, verbose_name= 'City Image')
The images are stored in media_files/images
The html:
<div id="main" class="container-fluid citybackground">
<!-- <img src="{{ MEDIA_URL}}{{ City.image.url }}"> -->
AS you can see I tried multiple options. The commented out section was a method I tried.
The css:
.citybackground
{
background-image: url( "{% images {{City.image.url}} %}");
background-repeat:no-repeat;
background-size:100%;
}
The views.py:
def SetCitySession(request):
if request.method == "POST":
request.session['city-name'] = request.POST['cityName']
request.session['city-id'] = request.POST['cityId']
return JsonResponse({})
def GetCitySession(request):
if request.method == "GET":
cityName = request.session['city-name']
cityId = request.session['city-id']
context = {
"cityName": cityName,
"cityId": cityId
}
return JsonResponse(context)
This is currently working hard coded javascript which I want to stop using since it isn't dynamic.
function changeBackground(city){
var urlBackground;
switch(city){
case "Manchester":
urlBackground = "/static/img/fondo_main.jpg";
break;
case "Liverpool":
urlBackground = "/static/img/liverpool_background.jpg";
break;
case "London":
urlBackground = "/static/img/london_background.jpg";
break;
}
$("#main").css("background-image", "url('{% if city.image %}{{ city.image.url }}{% else %}{"+ urlBackground + "}{% endif %}')";
}
Thanks ya'll
Simply write it as:
background-image: url({{ city.image.url }});
Use inline style for background image
<div id="main" class="container-fluid citybackground" style="background-image: url({{City.image.url}})">
I wrote this question when I was completely new to Django, finishing off an existing project whilst not fully understanding how the system worked. The answer by #yusuf.oguntula is correct in a manner. In the the question I neglected to add the view that actually showed the background image and rather gave the views which where used to retrieve and set session data on the server. Secondly, the actual view did not state which city it was since it had not retrieved the city from django. At the time the city was set by javascript but there was no query set or object retrieval within the view itself so as to allow interaction with python syntax. This meant even though the solution suggested by #yusuf.oguntula was correct it did not work due to the missing query set. I fixed this first by retrieving the appropriate city to the HomepageView in views.py like this:
if 'city-name' not in request.session:
cityName='Madrid'
request.session['city-name'] = request.POST.get('cityName')
else:
cityName = request.session['city-name']
city = get_object_or_404(City, name=cityName)
and then used #yusuf.oguntula 's solution in my html. It worked perfectly.
Add inline CSS to the element you want to have a background image. For example,
<div style="background: url('{{ home.image.url }}');">
</div>
This will work for sure

string being appended to image source in Chrome which prevents it from loading

My code looks something like
var publishedDate = Convert.ToDateTime(node.GetProperty("publishedDate").Value);
string image = Umbraco.Content(node.Id).GetPropertyValue("postImage").src;
string categories = #node.GetProperty("categories").Value.Replace(",", ", ");
<div class="column">
<img class="post-image" src="#image">
<div class="post-details" data-equalizer-watch>
<h5 class="post-category">#categories</h5>
<h2 class="post-title">#node.Name</h2>
<h6 class="post-date">#string.Format("{0:MMMM dd, yyyy}", publishedDate)</h6>
</div>
</div>
and when I view the image source in Chrome using developer tools, the image src will end up looking like
src="/media/8354/collegis_blogs_design_jr_7-23_15_news.jpg?1499808181609"
the appended string after the jpg is causing the image to error out. This does not occur in Internet Explorer since no string gets appended. Anyone have any idea why this could be occuring?
thanks,
Depending on which version of Umbraco you are using I would get the media path like this:
for v7.6 and above
string imageUrl = Model.Content.GetPropertyValue<IPublishedContent>("headerImage").Url;
for v7.5x and below
UmbracoHelper uHelper = new UmbracoHelper(UmbracoContext.Current);
string mediaUrl = "";
if (CurrentPage.HasValue(propertyName))
{
var mediaItem = uHelper.Media(CurrentPage.propertyName.ToString());
mediaUrl = mediaItem.umbracoFile;
}
return mediaUrl;
See my blog post about it and for how to do it from a controller.
http://www.codeshare.co.uk/blog/how-to-get-the-file-path-of-a-media-item-in-umbraco/

Easy way to replace parts of code with other parts of code

I'm making a small website for a game called League of Legends that compares matchup data (what champion counters a certain champs counters) and prints out results on a webpage. I'm using this html code that shows character portraits with onClick() to make them start a function when clicked
<a href="#" onClick="tristanaweak()"><img src="portraits/Aatrox_Square_0.png" width="25px" height="25px" alt=random></img>
<a href="#" onClick="tristanaweak()"><img src="portraits/Ahri_Square_0.png" width="25px" height="25px" alt=random></img>
<a href="#" onClick="tristanaweak()"><img src="portraits/Akali_Square_0.png" width="25px" height="25px" alt=random></img>
<a href="#" onClick="tristanaweak()"><img src="portraits/Alistar_Square_0.png" width="25px" height="25px" alt=random></img>
<a href="#" onClick="tristanaweak()"><img src="portraits/Amumu_Square_0.png" width="25px" height="25px" alt=random></img>
I've already manually put in the picture filenames (which was very tedious), but I still have to rename the onclick() values (tristanaweak) with the champion name (aatroxweak, ahriweak, etc.). I was thinking of doing this with a loop that edits text, but I don't know how I would go about doing this.
I'm fairly new to using Javascript, is there an easy way to rename all the onClick="tristanaweak()"'s in the html code to the first part of the png filenames in the same lines?
You can do this using PHP. First, create a list of all the champions:
$champs = "aatrox,arhi,akali,alistar,amumu,...";
Then do an explode to separate each champion and store it as an element in an array:
$pieces = explode(",", $champs);
echo $pieces[0]; //this will return aatrox
echo $pieces[1]; //this will return ahri
Now you can use a for loop to echo the desired results:
for($i=0;$i<count($pieces);$i++) {
echo '<!--other stuff here-->';
}
In the end, the result will be something like this:
<!--other stuff here-->
<!--other stuff here-->
etc, etc. I hope this is what you are looking for.
You should chose a different approach in my opinion. In javascript, you can also generate HTML dynamically using javascript function document.createElement(string tagName).
So, one of two possible soulitions would be creating a new images with new event for every champion:
HTML:
<div id="hero_images">
</div>
JS:
var champions = [
{
name: "Veigar",
callback: function() {/**Whatever you wanna do in onclick**/}
},
{
name: "Vladimir",
callback: function() {/**Whatever you wanna do in onclick**/}
},
{
name: "Morgana",
callback: function() {/**Whatever you wanna do in onclick**/}
}
];
//Now lets make an image for every champion:
var container = document.getElementById("hero_images"); //We'll put images in div I've defined in HTML above
for(var i=0; i<champions.length; i++) { //Loop through "champions" which is an array
var a = document.createElement("a");
a.href="#";
a.onclick = champions[i].callback; //Assign function from champion list to this <a>
//Also create the image
var img = document.createElement("img");
img.src = "portraits/"+champions[i].name+"_Square_0.png"; //I suppose image always have champion name in beginning
img.alt = champions[i].name; //Alternative text for no-image users
//Append image to link:
a.appendChild(img);
//Append <a> to <div>
contained.appendChild(a);
}
But in fact, you should use a global function for champions and you should have champion stats defined in the champions I've used. Under such circumstances:
var champions = [
{
name: "Veigar",
stats: {
inteligence: 666,
strength: 1,
/*..whatever you use...**/
}
}
];
for(/**imagine the prewious code here**/) {
...
a.onclick=(function(i) {
ShowHeroStatsOrWhatever(champions[i]);
})(i);
...
}
function ShowHeroStatsOrWhatever(champion) {
alert("Champions intelligence is "+champion.stats.inteligence);
}
Have you played around with jQuery .replaceWith();?
Description: Replace each element in the set of matched elements with
the provided new content and return the set of elements that was
removed.
Or the straight up javascript way (which I use with in conjunction with jQuery over the above 90% of the time) with .replace();
The replace() method searches a string for a specified value, or a
regular expression, and returns a new string where the specified
values are replaced.

Categories

Resources