Clear bootstrap cache - javascript

I developed a dynamic carousel. Within a form I show several records and the ID of these records is related to n number of images that I show in a carousel, making it have n number of the carousel with n number of images each.
The problem is in the visualization. When I start to play with the carousels several times, they start to show the superimposed images mixing both images, for example.
My question is, what should I "clean" when loading the images so that things like this don't happen?
I execute this function JavaScript, Ajax to arm the carousel:
function GetEvidenceScrap(id)
{
var idcompleto = id.id;
var i = 0;
var idbutton = idcompleto.substring(2, idcompleto.length);
$.ajax({
method: "GET",
url: "Coordinador/GetEvidenceScrap",
contentType: "aplication/json; Charset=utf-8",
data: { 'idscrap': idbutton },
async: true,
success: function (result) {
console.log("Longitud: " + result.length);
while (i < result.length)
{
var carousel = document.getElementById('CI_' + idbutton);
if (i == 0)
{
var div = document.createElement('div');
div.setAttribute('class','carousel-item active');
var img = document.createElement("img");
img.setAttribute('class', 'd-block w-100');
div.appendChild(img);
img.setAttribute('src', '/Evidence/' + result[i].rutevidencia);
carousel.appendChild(div);
i++;
}
else
{
var div = document.createElement('div');
div.setAttribute('class', 'carousel-item');
var img = document.createElement('img');
img.setAttribute('class', 'd-block w-100');
div.appendChild(img);
img.setAttribute('src', '/Evidence/' + result[i].rutevidencia);
carousel.appendChild(div);
i++;
}
}
console.log(result);
}
});
Function in C#:
[HttpGet]
public List<Evidencia> GetEvidenceScrap(int idscrap)
{
var idscrapparametro = new SqlParameter("#idscrap", idscrap);
var listaevidencescrap = _context.Evidencias.FromSqlRaw($"SELECT IDRegistro, IDScrap, rutevidencia FROM dbo.F_GetEvidenceScrap(#idscrap)", idscrapparametro);
return listaevidencescrap.ToList();
}
Thank you

Related

How to resize and display images in JavaScript

I am attempting to read images from a list of paths (10 items long) returned via an ajax function, resize each one and then display one after the other on the page. However, the below code only displays the first image (resized) and none of the others. I am fairly sure the resizing works as the printed sizes look correct. Below is my code in JavaScript:
// Helper function
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW && ratio <= 1) {
currW = maxW;
currH = currW * ratio;
} else if(currH >= maxH) {
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
function get_similar_images(image_name) {
console.log(image_name)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/get_similar",
dataType: "json",
async: true,
data: JSON.stringify({name: image_name}),
success: function(data) {
console.log(data);
image_list = data['images']
category = data['category']
for (var i=0; i<image_list.length; i++) {
var img = document.createElement("img");
img.src = "static/products/"+category+"/"+image_list[i];
var actualH;
var actualW;
var newH;
var newW;
img.onload = function(){
actualW = this.width;
actualH = this.height;
console.log(actualW, actualH)
var newSize = scaleSize(300, 300, actualW, actualH);
console.log(newSize)
img.width = newSize[0];
img.height = newSize[1];
document.getElementById('imageDiv').appendChild(img)
};
}
},
error: function(xhr, status, error) {
// console.log(xhr.responseText);
}
})
}
If we simplify your for loop like that :
var img = document.createElement("img");
img.src = image_list[0];
img.onload = function() {
console.log(img);
};
var img = document.createElement("img");
img.src = image_list[1];
img.onload = function() {
console.log(img);
};
You will understand where your mistake comes from. onload is an event, which means it's running asynchronously from your your code. You're updating img value with a new image element (and a new href attribute) before the first load event is triggered. Thus the onload event is actually called after the last update of the img variable, which actually happen when your reach the last loop of your for.
Why ?
Because a for loop doesn't create a new scope for the variable img, so each time you touch the img var, even if you're putting var in front, the original img is updated.
You should then use a function, because a function actually create a new scope for variables that are declared (var myVar) inside it :
function injectAndResize(imageUrl) {
var img = document.createElement("img");
img.src = imageUrl;
var actualH;
var actualW;
var newH;
var newW;
img.onload = function() {
actualW = this.width;
actualH = this.height;
var newSize = scaleSize(300, 300, actualW, actualH);
this.width = newSize[0];
this.height = newSize[1];
document.getElementById('imageDiv').appendChild(img);
};
}
for (var i = 0; i < image_list.length; i++) {
injectAndResize(image_list[i]);
}
There are a few issues in your code.
1) Image width and height are CSS properties and may be undefined in your img.onload handler. Use this.naturalWidth instead.
2) img.src = 'url'; triggers image load. Place it after img.onload.
success: function(data) {
console.log(data);
image_list = data.images;
category = data.category;
for (var i=0; i<image_list.length; i++) {
var img = document.createElement("img");
img.onload = function(){
var actualW = this.naturalWidth;
var actualH = this.naturalHeight;
console.log(actualW, actualH)
var newSize = scaleSize(300, 300, actualW, actualH);
console.log(newSize)
this.width = newSize[0];
this.height = newSize[1];
//also think what to do with images which are already there
//probably remove
document.getElementById('imageDiv').appendChild(this)
};//img.onload
img.src = "static/products/"+category+"/"+image_list[i];
}//for
},//success

imagecreatefromgif() from base64 encoded animated gif in POST

I am trying to make animated GIFs from media streams, videos, or images using the GifShot plugin.
My problem is that the ajax part does not see webcam_image_ajax.php. isn't working. Please do not hate me so the question will be a little longer.
I have to create this ajax function for uploading image:
var pos = 0, ctx = null, saveCB, gif = [];
var createGIFButton = document.createElement("canvas");
createGIFButton.setAttribute('width', 320);
createGIFButton.setAttribute('height', 240);
if (createGIFButton.toDataURL)
{
ctx = createGIFButton.getContext("2d");
gif = ctx.getImageData(0, 0, 320, 240);
saveCB = function(data)
{
var col = data.split(";");
var img = gif;
for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
}
if (pos >= 4 * 320 * 240)
{
ctx.putImageData(img, 0, 0);
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
function(data)
{
if($.trim(data) != "false")
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: $.base_url+"webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview').attr('id');
var T= M+','+values;
if(T!='undefinedd,')
$("#uploadvalues").val(T);
}
});
}
else
{
$("#webcam").html('<div id="camera_error"><b>Camera could not connect.</b><br/>Please be sure to make sure your camera is plugged in and in use by another application.</div>');
$("#webcam_status").html("<span style='color:#cc0000'>Camera not found please try again.</span>");
$("#webcam_takesnap").hide();
return false;
}
});
pos = 0;
}
else {
saveCB = function(data) {
gif.push(data);
pos+= 4 * 320;
if (pos >= 4 * 320 * 240)
{
$.post("webcam_image_ajax.php", {type: "pixel", gif: gif.join('|')},
function(data)
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: "webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview, .gifshot-image-preview-section').attr('id');
var T= M+','+values;
if(T!='undefined,')
$("#uploadvalues").val(T);
}
});
});
pos = 0;
}
};
}
};
}
$("#webcam").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "js/jscam_canvas_only.swf",
onSave: saveCB,
onCapture: function ()
{
webcam.save();
},
debug: function (type, string) {
$("#webcam_status").html(type + ": " + string);
}
});
});
/**Taking snap**/
function takeSnap(){
webcam.capture();
}
You can see this code in my ajax function:
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
the webcam_image_ajax.php is created in base64 format and then it upload the gif image from the images folder.
Also when clicked Create GIF button this JavaScript will starting: CLICK.
After that my ajax code have this line webcam_imageload_ajax.php
<?php
include_once 'includes.php';
if(isSet($_POST['webcam']))
{
$newdata=$Wall->Get_Upload_Image($uid,0);
echo "<img src='uploads/".$newdata['image_path']."' class='webcam_preview gifshot-image-preview-section' id='".$newdata['id']."'/>
";
}
?>
the webcam_imageload_ajax.php working with webcam_image_ajax.php.
If webcam_image_ajax.php created image then webcam_imageload_ajax.php echoing image like:
upload/14202558.gif
But now it looks like:
data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAABE...
creat a gif button:
<button type="button" id="create-gif" class="btn btn-large btn-primary create-gif-button camclick" onclick="return takeSnap();">Create GIF</button>
<input type="hidden" id="webcam_count" />
Forget the JavaScript code in the question.
If you want to use this script then use this code from demo.js inside in gifshot plugin.
function create_gif(data){
$.post(
"webcam_image_ajax.php",
{
data: data,
dataType: 'json'
},
function(js_data)
{
var js_d = $.parseJSON(js_data);
$('#gif_preview').attr('src', js_d.path);
if(js_d.id != 'error'){
$("#uploadvalues").val(js_d.id);
$('.webcam_preview, .gifshot-image-preview-section').attr('id', js_d.id);
}
}
);
}
and you can write your own php code for webcam_image_ajax.php.
Simply do like this:
file_put_contents('filename',file_get_contents(str_replace('data:','data://','<your base64 encoded data>')));
This is simply adapting your data:... into the data:// wrapper.
There is no simpler way to do this.
Notice that this is HIGHLY UNSECURE and you should validate the data (using preg_match for example) before usage.

Generic Javascript Image Swap

I'm building a navigation bar where the images should be swapped out on mouseover; normally I use CSS for this but this time I'm trying to figure out javascript. This is what I have right now:
HTML:
<li class="bio"><img src="images/nav/bio.jpg" name="bio" /></li>
Javascript:
if (document.images) {
var bio_up = new Image();
bio_up.src = "images/nav/bio.jpg";
var bio_over = new Image();
bio_over.src = "images/nav/bio-ov.jpg";
}
function over_bio() {
if (document.images) {
document["bio"].src = bio_over.src
}
}
function up_bio() {
if (document.images) {
document["bio"].src = bio_up.src
}
}
However, all of the images have names of the form "xyz.jpg" and "xyz-ov.jpg", so I would prefer to just have a generic function that works for every image in the navbar, rather than a separate function for each image.
A quick-fire solution which should be robust enough provided all your images are of the same type:
$("li.bio a").hover(function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace(".jpg", "") + "-ov.jpg";
}, function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace("-ov.jpg", "") + ".jpg";
});
This should work will all image formats as long as the extension is between 2 and 4 characters long IE. png, jpeg, jpg, gif etc.
var images = document.getElementById('navbar').getElementsByTagName('img'), i;
for(i = 0; i < images.length; i++){
images[i].onmouseover = function(){
this.src = this.src.replace(/^(.*)(\.\w{2,4})$/, '$1'+'-ov'+'$2');
}
images[i].onmouseout = function(){
this.src = this.src.replace(/^(.*)-ov(\.\w{2,4})$/, '$1'+'$2');
}
}
Here's an idea in plain javascript (no jQuery):
function onMouseOverSwap(e) {
e.src = e.src.replace(/\.jpg$/", "-ov.jpg"); // add -ov onto end
}
function onMouseOutSwap(e) {
e.src = e.src.replace(/(-ov)+\.jpg$/, ".jpg"); // remove -ov
}

Implementing a Preloader in Processingjs Canvas element

How do you implement a preloader for a processingjs canvas element?
Two cases - assets have loaded, but js still calculating/rendering the view; assets have not loaded
P.S. Someone create the processingjs tag! Users with rep lt 1500 can't do that yet :(
May be this very old snippet helps you, after loading all images a callback is called. The folder param was used to load low or highres pics.
pics = {
'Trans100' : "trans100.png",
'Trans101' : "trans101.png",
'TransPanel' : "transPanel.png"
}
function oAttrs(o) { var a, out = ""; for (a in o){ out += a + " ";} return trim(out);}
function imageLoader(pics, folder, onready){
this.nextPic = 0;
this.pics = pics;
this.folder = folder;
this.names = oAttrs(pics).split(" ");
this.onReady = onready;
this.loadNext();
}
imageLoader.prototype.loadNext = function (){
if (this.nextPic === this.names.length) {
this.onReady();
} else {
this.loadImage(this.pics[this.names[this.nextPic]]);
}
};
imageLoader.prototype.loadImage = function (file){
this.nextPic += 1;
var pic = new Image();
pic.onload = this.loadNext.bind(this);
pic.onerror = function(){console.error("ERROR: " + file);};
pic.src = this.folder + file;
};
// example:
new imageLoader(pics, "images", function(){
console.log("Images loaded");
})

Resizing dynamic images not working more than one time

I've got a little problem here. I've been trying to do an image gallery with JavaScript but there's something that I got a problem with. I can get the image to resize when the first image load, but as soon as I load another image, it won't resize anymore! Since the user will be able to upload a lot of different size pictures, I really need to make it work.
I've checked for ready-to-use image gallery and such and nothing was doing what I need to do.
Here's my javascript:
function changeCurrentImage(conteneur)
{
var img = conteneur.getElementsByTagName("img");
var imgUrl = img[0].src;
var imgFirstPart = imgUrl.substring(0, imgUrl.lastIndexOf('.') - 9);
var imgLastPart = imgUrl.substring(imgUrl.lastIndexOf('.'));
var currentImg = document.getElementById('currentImage');
currentImg.src = imgFirstPart + "borne" + imgLastPart;
resize(document.getElementById('currentImage'), 375, 655);
}
function resize(img, maxh, maxw) {
var ratio = maxh/maxw;
if (img.height/img.width > ratio){
// height is the problem
if (img.height > maxh){
img.width = Math.round(img.width*(maxh/img.height));
img.height = maxh;
}
} else {
// width is the problem
if (img.width > maxw){
img.height = Math.round(img.height*(maxw/img.width));
img.width = maxw;
}
}
};
Here's the HTML (using ASP.Net Repeater):
<asp:Repeater ID="rptImages" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<a href="#">
<div id="thumbnailImageContainer1" onclick="changeCurrentImage(this)">
<div id="thumbnailImageContainer2">
<img id="thumbnailImage" src="<%# SiteUrl + Eval("ImageThumbnailPath")%>?rn=<%=Random()%>" alt="Photo" onload="resize(this, 60, 105)" />
</div>
</div>
</a>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
Most likely the image is not yet downloaded so img.height and img.width are not yet there. Technically you don't need to wait till the whole image is downloaded, you can poll the image in a timer until width and height are non-zero. This sounds messy but can be done nicely if you take the time to do it right. (I have an ImageLoader utility I made for this purpose....has only one timer even if it is handling multiple images at once, and calls a callback function when it has the sizes) I have to disagree with Marcel....client side works great for this sort of thing, and can work even if the images are from a source other than your server.
Edit: add ImageLoader utility:
var ImageLoader = {
maxChecks: 1000,
list: [],
intervalHandle : null,
loadImage : function (callback, url, userdata) {
var img = new Image ();
img.src = url;
if (img.width && img.height) {
callback (img.width, img.height, url, 0, userdata);
}
else {
var obj = {image: img, url: url, callback: callback,
checks: 1, userdata: userdata};
var i;
for (i=0; i < this.list.length; i++) {
if (this.list[i] == null)
break;
}
this.list[i] = obj;
if (!this.intervalHandle)
this.intervalHandle = setInterval(this.interval, 30);
}
},
// called by setInterval
interval : function () {
var count = 0;
var list = ImageLoader.list, item;
for (var i=0; i<list.length; i++) {
item = list[i];
if (item != null) {
if (item.image.width && item.image.height) {
item.callback (item.image.width, item.image.height,
item.url, item.checks, item.userdata);
ImageLoader.list[i] = null;
}
else if (item.checks > ImageLoader.maxChecks) {
item.callback (0, 0, item.url, item.checks, item.userdata);
ImageLoader.list[i] = null;
}
else {
count++;
item.checks++;
}
}
}
if (count == 0) {
ImageLoader.list = [];
clearInterval (ImageLoader.intervalHandle);
delete ImageLoader.intervalHandle;
}
}
};
Example usage:
var callback = function (width, height, url, checks, userdata) {
// show stuff in the title
document.title = "w: " + width + ", h:" + height +
", url:" + url + ", checks:" + checks + ", userdata: " + userdata;
var img = document.createElement("IMG");
img.src = url;
// size it to be 100 px wide, and the correct
// height for its aspect ratio
img.style.width = "100px";
img.style.height = ((height/width)*100) + "px";
document.body.appendChild (img);
};
ImageLoader.loadImage (callback,
"http://upload.wikimedia.org/wikipedia/commons/thumb/" +
"1/19/Caerulea3_crop.jpg/800px-Caerulea3_crop.jpg", 1);
ImageLoader.loadImage (callback,
"http://upload.wikimedia.org/wikipedia/commons/thumb/" +
"8/85/Calliphora_sp_Portrait.jpg/402px-Calliphora_sp_Portrait.jpg", 2);
With the way you have your code setup, I would try and call your resize function from an onload event.
function resize() {
var img = document.getElementById('currentImage');
var maxh = 375;
var maxw = 655;
var ratio = maxh/maxw;
if (img.height/img.width > ratio){
// height is the problem
if (img.height > maxh){
img.width = Math.round(img.width*(maxh/img.height));
img.height = maxh;
}
} else {
// width is the problem
if (img.width > maxw){
img.height = Math.round(img.height*(maxw/img.width));
img.width = maxw;
}
}
};
function changeCurrentImage(conteneur)
{
var img = conteneur.getElementsByTagName("img");
img.onload = resize;
var imgUrl = img[0].src;
var imgFirstPart = imgUrl.substring(0, imgUrl.lastIndexOf('.') - 9);
var imgLastPart = imgUrl.substring(imgUrl.lastIndexOf('.'));
var currentImg = document.getElementById('currentImage');
currentImg.src = imgFirstPart + "borne" + imgLastPart;
}
I would play around with that. Maybe use global variables for your maxH/W and image ID(s);
#Comments: No, I can't do that server side since it would refresh the page everytime someone click on a new image. That would be way too bothersome and annoying for the users.
As for the thumbnails, those image are already saved in the appropriate size. Only the big image that shows is about 33% of its size. Since we already have 3 images PER uploaded images, I didn't want to upload a 4th one for each upload, that would take too much server space!
As for the "currentImage", I forgot to add it, so that might be helful lol:
<div id="currentImageContainer">
<div id="currentImageContainer1">
<div id="currentImageContainer2">
<img id="currentImage" src="#" alt="" onload="resize(this, 375, 655)" />
</div>
</div>
</div>
#rob: I'll try the ImageLoader class, that might do the trick.
I found an alternative that is working really well. Instead of changing that IMG width and height, I delete it and create a new one:
function changeCurrentImage(conteneur)
{
var thumbnailImg = conteneur.getElementsByTagName("img");
var thumbnailImgUrl = thumbnailImg[0].src;
var newImgUrl = thumbnailImgUrl.replace("thumbnail", "borne");
var currentImgDiv = document.getElementById('currentImageContainer2');
var currentImg = currentImgDiv.getElementById("currentImage");
if (currentImg != null)
{
currentImgDiv.removeChild(currentImg);
}
var newImg = document.createElement("img");
newImageDiv = document.getElementById('currentImageContainer2');
newImg.id = "currentImage";
newImg.onload = function() {
Resize(newImg, 375, 655);
newImageDiv.appendChild(newImg);
}
newImg.src = newImgUrl;
}
Also, in case people wonder, you MUST put the .onload before the .src when assigning an a new source for an image!

Categories

Resources