ReferenceError: PDFJS is not defined Asp.net - javascript

I'm trying to display a pdf using canvas and PDF.JS Stable v.2.2.228 but when I execute my webform it shows this error in the console: ReferenceError: PDFJS is not defined.
I read something about the global PDFJS object being removed but I can't find the correct syntax [Kinda new in JS]. Any suggestion is very appreciated
I was following this example in case is needed : https://usefulangle.com/post/20/pdfjs-tutorial-1-preview-pdf-during-upload-wih-next-prev-buttons
Js code:
function showPDF(pdf_url) {
PDFJS.getDocument({ url: pdf_url }).then(function (pdf_doc) {
__PDF_DOC = pdf_doc;
__TOTAL_PAGES = __PDF_DOC.numPages;
// Show the first page
showPage(1);
}).catch(function (error) {
// If error re-show the upload button
alert(error.message);
});;
}
function showPage(page_no) {
__PAGE_RENDERING_IN_PROGRESS = 1;
__CURRENT_PAGE = page_no;
__PDF_DOC.getPage(page_no).then(function (page) {
// As the canvas is of a fixed width we need to set the scale of the viewport accordingly
var scale_required = __CANVAS.width / page.getViewport(1).width;
// Get viewport of the page at required scale
var viewport = page.getViewport(scale_required);
// Set canvas height
__CANVAS.height = viewport.height;
var renderContext = {
canvasContext: __CANVAS_CTX,
viewport: viewport
};
page.render(renderContext).then(function () {
__PAGE_RENDERING_IN_PROGRESS = 0;
// Show the canvas and hide the page loader
$("#pdf-canvas").show();
});
});
}
function ValidateFileUpload() {
var fuData = document.getElementById('FileUpload1');
var FileUploadPath = fuData.value;
//To check if user upload any file
if (FileUploadPath == '') {
alert("Por favor subir un archivo");
} else {
var Extension = FileUploadPath.substring(
FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "png" || Extension == "jpeg" || Extension == "jpg" || Extension == "gif" || Extension == "jfif") {
// To Display
if (fuData.files && fuData.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#ImgPreview').attr('src', e.target.result);
//document.getElementById('ImgPreview').files[0].name;
var nombre= document.getElementById('ImgPreview').files[0].name;
document.querySelector('#LblFileupload').innerText = nombre;
}
reader.readAsDataURL(fuData.files[0]);
}
}
else if (Extension == "pdf") {
var __PDF_DOC,
__CURRENT_PAGE,
__TOTAL_PAGES,
__PAGE_RENDERING_IN_PROGRESS = 0,
__CANVAS = $('#pdf-canvas').get(0),
__CANVAS_CTX = __CANVAS.getContext('2d');
showPDF(URL.createObjectURL($("#FileUpload1").get(0).files[0]));
}
//The file upload is NOT an image
else {
alert("Solo se aceptan archivos en formato .JPG - .PNG - .JPEG - .GIF - .JFIF");
}
}
}
HTML :
<asp:FileUpload ID="FileUpload1" runat="server" accept="image/*" onchange="return ValidateFileUpload()" Visible="true" />
<asp:Image ID="ImgPreview" runat="server" Height="600px" Width="500px" />
<canvas id="pdf-canvas" width="400"> </canvas>

You should change PDFJS to pdfjsLib. Also you should try adding the lines var __CANVAS = $('#pdf-canvas').get(0); and var __CANVAS_CTX = __CANVAS.getContext('2d'); under __CURRENT_PAGE = page_no; in that function because you're not initializing those variables before you try to call and use them. Also you need to add var in front of the other two items you're using in that function at the top.
So it should look like:
pdfjsLib.getDocument(URL.createObjectURL($("#FileUpload1").get(0).files[0])).then(doc => {
console.log("This file has " + doc._pdfInfo.numPages + "pages");
doc.getPage(1).then(page => {
var myCanvas = document.getElementById('pdf-canvas');
var context = myCanvas.getContext('2d');
var viewport = page.getViewport(1);
myCanvas.width = viewport.width;
myCanvas.height = viewport.height;
page.render({
canvasContext: context,
viewport : viewport
}
);
});
});

Related

How to detect, that drawing a canvas object is finished?

I have following JS code (found here, on stackoverflow, and a little-bit modded), which resize image on client side using canvas.
function FileListItem(a) {
// Necesary to proper-work of CatchFile function (especially image-resizing).
// Code by Jimmy Wärting (https://github.com/jimmywarting)
a = [].slice.call(Array.isArray(a) ? a : arguments)
for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File
if (!d) throw new TypeError('expected argument to FileList is File or array of File objects')
for (b = (new ClipboardEvent('')).clipboardData || new DataTransfer; c--;) b.items.add(a[c])
return b.files
}
function CatchFile(obj) {
// Based on ResizeImage function.
// Original code by Jimmy Wärting (https://github.com/jimmywarting)
var file = obj.files[0];
// Check that file is image (regex)
var imageReg = /[\/.](gif|jpg|jpeg|tiff|png|bmp)$/i;
if (!file) return
var uploadButtonsDiv = document.getElementById('upload_buttons_area');
// Check, that it is first uploaded file, or not
// If first, draw a div for showing status
var uploadStatusDiv = document.getElementById('upload_status_area');
if (!uploadStatusDiv) {
var uploadStatusDiv = document.createElement('div');
uploadStatusDiv.setAttribute('class', 'upload-status-area');
uploadStatusDiv.setAttribute('id', 'upload_status_area');
uploadButtonsDiv.parentNode.insertBefore(uploadStatusDiv, uploadButtonsDiv.nextSibling);
// Draw sub-div for each input field
var i;
for (i = 0; i < 3; i++) {
var uploadStatus = document.createElement('div');
uploadStatus.setAttribute('class', 'upload-status');
uploadStatus.setAttribute('id', ('upload_status_id_commentfile_set-' + i + '-file'));
uploadStatusDiv.append(uploadStatus);
}
}
var canvasDiv = document.getElementById('canvas-area');
var currField = document.getElementById(obj.id);
var currFieldLabel = document.getElementById(('label_' + obj.id));
// Main image-converting procedure
if (imageReg.test(file.name)) {
file.image().then(img => {
const canvas = document.createElement('canvas')
canvas.setAttribute('id', ('canvas_' + obj.id));
const ctx = canvas.getContext('2d')
const maxWidth = 1600
const maxHeight = 1200
// Calculate new size
const ratio = Math.min(maxWidth / img.width, maxHeight / img.height)
const width = img.width * ratio + .5|0
const height = img.height * ratio + .5|0
// Resize the canvas to the new dimensions
canvas.width = width
canvas.height = height
// Drawing canvas-object is necessary to proper-work
// on mobile browsers.
// In this case, canvas is inserted to hidden div (display: none)
ctx.drawImage(img, 0, 0, width, height)
canvasDiv.appendChild(canvas)
// Get the binary (aka blob)
canvas.toBlob(blob => {
const resizedFile = new File([blob], file.name, file)
const fileList = new FileListItem(resizedFile)
// Temporary remove event listener since
// assigning a new filelist to the input
// will trigger a new change event...
obj.onchange = null
obj.files = fileList
obj.onchange = CatchFile
}, 'image/jpeg', 0.70)
}
)
// If file is image, during conversion show status
function ShowConvertConfirmation() {
if (document.getElementById('canvas_' + obj.id)) {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>';
return true;
}
else {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>';
return false;
}
}
// Loop ShowConvertConfirmation function untill return true (file is converted)
var convertConfirmationLoop = setInterval(function() {
var isConfirmed = ShowConvertConfirmation();
if (!isConfirmed) {
ShowConvertConfirmation();
}
else {
// Break loop
clearInterval(convertConfirmationLoop);
}
}, 2000); // Check every 2000ms
}
// If file is not an image, show status with filename
else {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Dodano plik ' + file.name + '</font>';
//uploadStatusDiv.append(uploadStatus);
}
}
Canvas is drawn in hidden div:
<div id="canvas-area" style="overflow: hidden; height: 0;"></div>
I am only detect, that div canvas-area is presented and basing on this, JS append another div with status.
Unfortunatelly on some mobile devices (mid-range smartphones), message will be showed before finish of drawing (it is wrong). Due to this, some uploaded images are corrupted or stay in original size.
How to prevent this?
Everything that should happen after the image has loaded, should be executed within the then callback, or called from within it.
It is important to realise that the code that is not within that callback will execute immediately, well before the drawing has completed.

PDF.js get images of one page and display them as HTML

according to this: [Extract images from PDF file with JavaScript
I tried to filter the JPEG images from PDF. It works in the way, that I get the name of the images of one page in an array.
What I want to do: Display the images next to the PDF as HTML . The solution mentioned above doesn't work, I do not know, how to get the image itself and not just the name.
<script type="text/javascript" src="pdf.js"></script>
<script type="text/javascript">
PDFJS.workerSrc = "/path/to/pdf.worker.js";
</script>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas" style="width: 500px;"></canvas>
<div id="images"></div>
<script type="text/javascript">
PDFJS.workerSrc = "pdf.worker.js";
</script>
<script src="js.js"></script>
js.js:
// URL of PDF document
var url = "test/pdf_one.pdf";
var pageNum = 11;
var pageCount = 0;
loadPage(pageNum);
function loadPage(number){
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
pageCount = pdf.numPages;
document.getElementById("page_num").innerHTML = "" + pageNum;
document.getElementById("page_count").innerHTML = "" + pageCount;
return pdf.getPage(number);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
getImages(page);
});
}
function getImages(page){
var test = [];
page.getOperatorList().then(function (ops) {
for (var i=0; i < ops.fnArray.length; i++) {
if (ops.fnArray[i] == PDFJS.OPS.paintJpegXObject) {
console.log(ops.argsArray[i][0]);
document.getElementById("images").innerHTML = "<img src='"+ops.argsArray[i][0]+".jpg'>";
test.push(ops.argsArray[i][0])
}
}
});
console.log(test);
if(pageNum === 13){
console.log("IMAGES");
console.log(test[0]);
document.getElementById("images").innerHTML = "<img src='"+test[0]+".jpg'>";
}
}
document.getElementById('prev').addEventListener('click', onPrevPage);
document.getElementById('next').addEventListener('click', onNextPage);
function onNextPage() {
if (pageNum >= pageCount) {
return;
}
pageNum++;
document.getElementById("page_num").innerHTML = "" + pageNum;
loadPage(pageNum);
}
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
document.getElementById("page_num").innerHTML = "" + pageNum;
loadPage(pageNum);
}

Jquery validating - comparing the content of jquery variables

I am writing a script which allows users to up load image files. Each user has an account to login and when they do so a data table is read and returns a list of screens associated to their account.
The user selects a screen and a jQuery script returns the screen resolution.
var w;
var h;
$(document).ready(function()
{
$('#board').change(function(){
$.get('check_override_image.php', { RecordID: form2.board.value },
function(result) {
result = JSON.parse(result);
w = result["imagesizes"][0]["DisplayWidth"];
h = result["imagesizes"][0]["DisplayHeight"];
$('#size').html("Display width: " + result["imagesizes"][0]["DisplayWidth"]
+ ",<br> Display height: " + result["imagesizes"][0]["DisplayHeight"]).show();
if (result["imagesizes"][0]["DisplayType"] == 'P' ) {
$("#portrait").show();
$("#landscape").hide();
$("#SelectView").show();
$("#SelectViewText").show();
} else {
$("#landscape").show();
$("#portrait").hide();
$("#SelectView").show();
$("#SelectViewText").show();
}
});
});
});
The user clicks on a "Browse" link to select an image from their local drive and another jQuery script returns the image filename and the image dimensions.
$(document).ready(function(){
//LOCAL IMAGE
var _URL = window.URL || window.webkitURL;
$("#image_field").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
if ( this.width != w || this.height != y) {
alert(this.width + " " + this.height);
};
};
img.src = _URL.createObjectURL(file);
}
});
});
My question: is there a way I can use the result["imagesizes"][0]["DisplayWidth"]and result["imagesizes"][0]["DisplayHeight"] along with "this.width" and "this.height" to make sure the the selected image dimensions are the same as the selected screen resolution?
I worked out how this is done and updated my question code to reflect

How to get image width and height using JavaScript before upload?

How to get image width and height using Javascript before upload? I tried to test my code, but it does not work. How can I achieve this?
https://jsfiddle.net/r78qkjba/1/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input name="offer_image_1" onchange="check_thumbnail_image_format_fn()" type="file" id="offer_image_1" />
<script>
function check_thumbnail_image_format_fn() {
var offer_image_1_data = document.getElementById("offer_image_1");
var offer_image_1_data_file = offer_image_1_data.files[0];
var offer_image_1_data_file_width = offer_image_1_data_file.width;
var offer_image_1_data_file_height = offer_image_1_data_file.height;
alert(offer_image_1_data_file_width);
alert(offer_image_1_data_file_height);
};
</script>
HTML5 and the File API
Here's the uncommented working code snippet example:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
elPreview = document.getElementById("preview"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
var imageInfo = file.name +' '+
image.width +'×'+
image.height +' '+
file.type +' '+
Math.round(file.size/1024) +'KB';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file); // Free memory
}
});
reader.readAsDataURL(file);
}
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
#preview img{height:100px;}
<input id="browse" type="file" multiple />
<div id="preview"></div>
Using an input and a div for the images preview area
<input id="browse" type="file" multiple>
<div id="preview"></div>
let's also use a CSS to keep the resulting images a reasonable height:
#preview img{ height:100px; }
JavaScript:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
elPreview = document.getElementById("preview"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
// 2.
function readImage (file) {
// 2.1
// Create a new FileReader instance
// https://developer.mozilla.org/en/docs/Web/API/FileReader
var reader = new FileReader();
// 2.3
// Once a file is successfully readed:
reader.addEventListener("load", function () {
// At this point `reader.result` contains already the Base64 Data-URL
// and we've could immediately show an image using
// `elPreview.insertAdjacentHTML("beforeend", "<img src='"+ reader.result +"'>");`
// But we want to get that image's width and height px values!
// Since the File Object does not hold the size of an image
// we need to create a new image and assign it's src, so when
// the image is loaded we can calculate it's width and height:
var image = new Image();
image.addEventListener("load", function () {
// Concatenate our HTML image info
var imageInfo = file.name +' '+ // get the value of `name` from the `file` Obj
image.width +'×'+ // But get the width from our `image`
image.height +' '+
file.type +' '+
Math.round(file.size/1024) +'KB';
// Finally append our created image and the HTML info string to our `#preview`
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
// If we set the variable `useBlob` to true:
// (Data-URLs can end up being really large
// `src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAA...........etc`
// Blobs are usually faster and the image src will hold a shorter blob name
// src="blob:http%3A//example.com/2a303acf-c34c-4d0a-85d4-2136eef7d723"
if (useBlob) {
// Free some memory for optimal performance
window.URL.revokeObjectURL(file);
}
});
// 2.2
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
reader.readAsDataURL(file);
}
// 1.
// Once the user selects all the files to upload
// that will trigger a `change` event on the `#browse` input
elBrowse.addEventListener("change", function() {
// Let's store the FileList Array into a variable:
// https://developer.mozilla.org/en-US/docs/Web/API/FileList
var files = this.files;
// Let's create an empty `errors` String to collect eventual errors into:
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
// Check for `files` (FileList) support and if contains at least one file:
if (files && files[0]) {
// Iterate over every File object in the FileList array
for(var i=0; i<files.length; i++) {
// Let's refer to the current File as a `file` variable
// https://developer.mozilla.org/en-US/docs/Web/API/File
var file = files[i];
// Test the `file.name` for a valid image extension:
// (pipe `|` delimit more image extensions)
// The regex can also be expressed like: /\.(png|jpe?g|gif)$/i
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
// SUCCESS! It's an image!
// Send our image `file` to our `readImage` function!
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
// Notify the user for any errors (i.e: try uploading a .txt file)
if (errors) {
alert(errors);
}
});
Hope below code will help you.
var _URL = window.URL || window.webkitURL;
$("#offer_image_1").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert(this.width + " " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
You don't need to add onchange event at the input node.
This code is taken from
Check image width and height before upload with Javascript

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