How to detect if the image path is valid? - javascript

I have found a question regarding the images
How to detect if the image path is broken?
I have tried the following codes
var image = new Image;
image.src = "http://project" + path + '.png';
image.onload = function(){
var imageWidth = this.width + this.height;
if(imageWidth==0){
image.src = "http://project2" + path + '.png';
//the project2 path could be broken too and
//I want to use project3 or project4 as the
//path and keep testing it, but there is no way to do it from here.
}
}
Would it be possible to do a recursive test here? Thanks a lot!

You could try this setup:
var paths = ["/img1", "/img2", "/img3"];
var beginning = "http://project";
var ending = ".png";
function getImage(images, prefix, suffix, callback) {
var iterator = function (i) {
if (i < images.length) {
var image = new Image();
image.onload = function () {
var imageWidth = this.width + this.height;
if (imageWidth === 0) {
console.log("onload problem");
iterator(++i);
} else {
console.log("onload good");
callback(i, image);
}
};
image.onerror = function () {
console.log("onerror");
iterator(++i);
};
image.src = prefix + images[i] + suffix;
}
};
iterator(0);
}
getImage(paths, beginning, ending, function (index, img) {
console.log("Callback: ", index, ", ", img);
});
DEMO: http://jsfiddle.net/2mRMr/2/

Broken images would call onerror, not onload.
image.onerror = function () {
console.log("broken");
callToTryNewSrc();
}
Basic recursive check
function getImage(path, callback) {
//if numeric
var ind = 1;
var maxServer = 5;
//if named differently
//var ind = 0;
//var servers = ["//foo1","//foo2","//bar1"];
//var maxServer = servers.length-1;
function test() {
var img = new Image();
img.onload = function () {
if (callback) {
callback(img);
}
}
img.onerror = function () {
if (ind <= maxServer) {
test();
} else {
if (callback) {
callback(img);
}
}
}
var currentPath = "http://project" + ind + path + '.png';
//var currentPath = servers[ind] + path + '.png';
img.src = currentPath;
ind++;
}
test();
}
//calling it
getImage("/foo", function (img) {
console.log(img);
});

Related

Async checking image width and height and if they are OK, preview image

I'm trying to check width and height from an input file's images and check if they are at least equal than specific dimension (w:300px, h:300px).
I have this check:
window.onload = function () {
var fileUpload = document.getElementById("inputFileID");
fileUpload.onchange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("divToShowThumbs");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var file = fileUpload.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.src = e.target.result;
dvPreview.appendChild(img);
}
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
}
};
This works ok to preview each image.
But when I try to use "IF - ELSE" using img.width, it returns 0 because it works in asynchronous way!
Any light about how can I solve this situation?
All I'm trying to do is read each image, check if they area 300px (height and width) and if Ok, create the preview!
I got help from this - Getting width & height of an image with filereader . And here is your modified script.
window.onload = function () {
var fileUpload = document.getElementById("inputFileID");
fileUpload.onchange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("divToShowThumbs");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var file = fileUpload.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.src = e.target.result;
img.onload = function() {
// access image size here
console.log(this.width + " " + this.height);
if(this.width <=300 && this.height <=300 ) {
dvPreview.appendChild(img);
}
else {
alert("too big an image!");
}
};
};
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
};
};

Why does my redirect is not working?

my script calls my redirect function to early, so the last file of a batch upload is failing. I have been search the whole morning an tried different approaches, but without success.
function uploadFile(something, callback) {
var fileInput = $('#fileList1');
//var reader = new FileReader();
console.log(fileInput);
if ( trim( fileInput.val() ).length == 0 ) {
return;
}
var fileList = [];
count = fileInput[0].files.length;
for(i = 0; i < count; i++){
loadFile(fileInput[0].files[i]);
}
function loadFile(file){
var reader = new FileReader();
var fileName = getFileNameWithExtension( file);
var file = file;
while(reader.onprogress){
console.log("reading");
}
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
if (!--count){
redirect();
}
}
reader.onerror = function(event) {
console.error("File could not be read! Code " + reader.error.message);
}
reader.readAsDataURL(file);
}
}
function redirect(){
window.location.href = '/{!tempID}';
return false;
}
Can someone give me a hint?
#
Hello, i have rewritten my methods a bit based on your suggestions. But the redirect is still called to early,...before all uploads are done.
function uploadFile() {
var fileInput = $('#fileList1');
console.log(fileInput);
if ( trim( fileInput.val() ).length == 0 ) {
return;
}
var countTwo = 0;
count = fileInput[0].files.length;
for(var i = 0; i < count; i++){
loadFile(fileInput[0].files[i], function(val){
console.log(val);
if(val === 3){
setTimeout(()=>{redirect();}, 5000);
}
});
}
function loadFile(file, callback){
var reader = new FileReader();
var fileName = getFileNameWithExtension( file);
var file = file;
while(reader.onprogress){
console.log("reading");
}
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
console.log(" ct " + countTwo + " c " + count-1);
countTwo++;
if(!--count) callback(countTwo);
}
reader.onerror = function(event) {
console.error("File could not be read! Code " + reader.error.message);
}
reader.readAsDataURL(file);
}
}
Method 1: (Recommended)
Detect when your uploading ends. And in that callback, call redirect.
Method 2:
// define your TIMEOUT first
setTimeout(()=>{redirect();}, TIMEOUT);
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
if (!--count){
setTimeout(()=>{redirect();}, 0);
}
}

onload function in javascript not working Android

I am trying to read a image as a file and then display the image name,size etc. I debugged my code and found my onload function is loading but not working. Thank you for your help. I have included my whole FileSelection() method.
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
var iMaxFilesize = 1048576; // 1MB
var oTimer = 0;
var sResultFileSize = '';
var oImage = new Image();
function fileSelected() {
alert("hello");
// hide different warnings
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
// get selected file element
var oFile = document.getElementById('image_file').files[0];
// filter for image files
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! rFilter.test(oFile.type)) {
alert("problem");
document.getElementById('error').style.display = 'block';
return;
}
// little test for filesize
if (oFile.size > iMaxFilesize) {
document.getElementById('warnsize').style.display = 'block';
return;
}
// get preview element
oImage = document.getElementById('preview');
alert("hello2");
// prepare HTML5 FileReader
var oReader = new FileReader();
alert("hello3")
oReader.onload = function(e)
{
alert("hello4");
alert("reached");
oImage.onload = function () { // binding onload event
alert("hi");
// oImage.src = e.target.result;
// we are going to display some custom image information here
sResultFileSize = bytesToSize(oFile.size);
document.getElementById('fileinfo').style.display = 'block';
document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
};
// e.target.result contains the DataURL which we will use as a source of the image
oImage.src = e.target.result;
};
alert("file found");
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
Giving you the changes I was talking about in the comments:
//You want this somewhere
var oImage = new Image();
var oReader = new FileReader();
alert("hello3")
oReader.onload = function(e)
{
alert("hello4");
oImage.onload = function () { // binding onload event
alert("hi");
// we are going to display some custom image information here
sResultFileSize = bytesToSize(oFile.size);
document.getElementById('fileinfo').style.display = 'block';
document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
};
// Make sure this comes after
oImage.src = e.target.result;
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);

have been trying to create an mpeg dash player using but video is not responding

please check this code out and help me see what am doing wrong the file wont play in video. the segments are first appended to an array and then appended to the source buffer when the sourcebuffer updateend is called
$(function() {
var video = function () {
this.segmentArray = [];
this.version = "PressPause 1.0.0",
this.videoPlayer = document.querySelectorAll("video")[0];
this.source = new MediaSource();
this.segmentCheck = 0;
this.lastTime = 0;
this.duration = 0;
this.bandwidth = 0;
this.duration = "";
this.InitializationSegment = null;
this.mpdfile = null;
this.baseurl = "";
this.playingSegmentIndex = 0;
this.bufferUpdated = false;
this.initRange = 0;
this.width = 200;
this.height = 200;
this.segments = 0;
this.period = 0;
this.duration = 0;
this.codecs = String.EMPTY;
this.representation = null;
this.videoPlayer.src = this.mediaUrl;
this.videoPlayer.pause();
this.videoPlayer.width = this.width;
this.videoPlayer.height = this.height;
var self = this;
this.videoPlayer.addEventListener("play", function() {
console.log("from videoplayer play event");
});
self.videoPlayer.addEventListener("canplay", function () {
console.log("can play");
self.videoPlayer.play();
});
self.videoPlayer.addEventListener("loadstart", function () {
console.log("started loading metadate");
});
self.videoPlayer.addEventListener("onloadedmetadata", function() {
console.log("loaded metadata");
});
self.videoPlayer.addEventListener("oncanplaythrough", function() {
console.log("can play through");
});
self.videoPlayer.addEventListener("sourceended", function() {
console.log("has ended");
});
self.videoPlayer.addEventListener("onaddtrack", function() {
console.log("added track");
});
self.videoPlayer.addEventListener("play", function() {
console.log("called play");
});
self.videoPlayer.addEventListener("update", function() {
console.log("updated");
});
self.videoPlayer.addEventListener("loadeddata", function() {
console.log("has loaded data");
});
//this.sourceBuffer= null;o
this.startInit = false;
this.source.addEventListener("sourceopen", function() {
console.log("source has opened " + self.source.readyState);
});
this.source.addEventListener("sourceopen", this.init.call(self), false);
this.source.addEventListener("sourceclose", function() {
console.log("mediasource closed " +self.source.readyState);
}, false);
this.source.addEventListener("sourceended", function () {
console.log("mediasource ended "+self.source.readyState);
}, false);
this.source.addEventListener("endOfStream", function() {
console.log("have come to end of stream");
});
this.sourceBuffer = null;
}
video.prototype.timeToDownLoad = function (range) {
var videoself = this;
var vidDur = range.split("-");
// Time = size * 8 / bitrate
return (((vidDur[1] - vidDur[0]) * 8) / videoself.bandwidth);
}
video.prototype.fetchMpd = function (filename) {
if (this.startInit == false) {
this.startInit = true;
var videoself = this;
var httprequest = new XMLHttpRequest();
httprequest.open("GET", "PressPause/Media/" + filename + "mpd");
httprequest.send();
httprequest.onreadystatechange = function() {
var self = this;
if (self.readyState == 4) {
if (self.status == 200) {
videoself.mpdfile = new DOMParser().parseFromString(self.responseText, "application/xml");
videoself.processMpd.call(videoself,videoself.mpdfile);
}
}
};
}
}
video.prototype.processDuration = function(durationTemp) {
var worker = durationTemp.split("PT")[1];
var hour = worker.split("H")[0].slice(0, 1);
var mins = worker.split("H")[1].slice(0, 2);
var secss = worker.split("M")[1].slice(0, 5);
console.log("the hour is " + hour +" mins "+mins+ " secs "+secss);
};
video.prototype.processMpd=function(mpd) {
this.InitializationSegment = mpd.querySelectorAll("Initialization")[0];
this.initRange = this.InitializationSegment.getAttribute("range");
this.period = mpd.querySelectorAll("Period")[0];
var tempduration = this.period.getAttribute("duration");
this.processDuration(tempduration);
this.representation = mpd.querySelectorAll("Representation")[0];
this.bandwidth = this.representation.getAttribute("bandwidth");
this.videoPlayer.width = this.representation.getAttribute("width");
this.videoPlayer.height = this.representation.getAttribute("height");
this.codecs = this.representation.getAttribute("codecs");
this.segments = mpd.querySelectorAll("SegmentURL");
this.processRange(this.initRange);
this.startInitialization("the url", this.initRange);
console.log(this.initRange);
}
video.prototype.startInitialization = function (url, range) {
var videoSelf = this;
while (videoSelf.source.readyState!="open") {
console.log("mediaSource not open");
}
var codecs = 'video/mp4;codecs="avc1.64001E"';
console.log("can play codec " + codecs + videoSelf.videoPlayer.canPlayType(codecs));
//'video/mp4;codecs="' + videoSelf.codecs + '"'
videoSelf.sourceBuffer = videoSelf.source.addSourceBuffer(codecs);
videoSelf.sourceBuffer.addEventListener("updateend", function () {
console.log("updateend occurs when the append or remove operation has ended");
console.log("append mode " + videoSelf.sourceBuffer.AppendMode);
console.log("buffered below");
console.log(videoSelf.sourceBuffer.buffered);
console.log(videoSelf.sourceBuffer.updating);
});
videoSelf.sourceBuffer.addEventListener("update", function () {
console.log("update occurs when the append or remove operation has ended successfully");
console.log("append mode " +videoSelf.sourceBuffer.AppendMode);
console.log("buffered below");
console.log(videoSelf.sourceBuffer.buffered);
console.log(videoSelf.sourceBuffer.updating);
});
videoSelf.sourceBuffer.addEventListener("error", function () {
console.log("error occurs when the append or remove operation is aborted by calling abort");
console.log("append mode " + videoSelf.sourceBuffer.AppendMode);
console.log("buffered below");
console.log(videoSelf.sourceBuffer.buffered);
console.log(videoSelf.sourceBuffer.updating);
});
if (url && range) {
console.log("start processing");
var httprequest = new XMLHttpRequest();
httprequest.open("GET", "PressPause/Media/videomp4", true);
httprequest.responseType = "arrayBuffer";
httprequest.setRequestHeader("Range", "bytes=" + range);
httprequest.send();
httprequest.addEventListener("readystatechange", function() {
if (this.readyState == 4) {
if (this.status == 200) {
try {
videoSelf.sourceBuffer.appendBuffer(new Uint8Array(httprequest.response));
videoSelf.videoPlayer.readyState = 2;
videoSelf.videoPlayer.pause();
videoSelf.videoPlayer.play();
console.log("source is "+videoSelf.source.readyState);
console.log("player is " + videoSelf.videoPlayer.readyState);
console.log("player error is " + videoSelf.videoPlayer.error);
videoSelf.sourceBuffer.addEventListener("updateend", videoSelf.startProcessingSegments.bind(videoSelf));
} catch (e) {
console.log(e.message + "from startInitialization " + e);
}
}
}
});
} else {
throw new Error("range and url cannot be undefined");
}
}
video.prototype.startProcessingSegments = function () {
var self = this;
console.log(self);
console.log("starting to fetch data");
self.sourceBuffer.addEventListener("updateend", self.isupdating.bind(self), false);
self.isupdating.call(self);
console.log("from startProcessingSegments " + self.source.activeSourceBuffers);
console.log("from startProcessingSegments " + self.playingSegmentIndex);
console.log("can play type= " + self.videoPlayer.canPlayType('video/mp4;codecs="' + self.codecs + '"'));
self.bufferUpdated = true;
console.log(self.source.sourceBuffers);
console.log(self.sourceBuffer.buffered);
}
video.prototype.isupdating = function () {
var self = this;
self.videoPlayer.removeEventListener("updateend", self.startProcessingSegments);
for (self.playingSegmentIndex; self.playingSegmentIndex < self.segments.length; self.playingSegmentIndex++) {
console.log(self.sourceBuffer.updating);
self.checkSegmentArray.call(self);
self.playSegment("url", self.segments[self.playingSegmentIndex].getAttribute("mediaRange"));
}
};
video.prototype.addingSegmentIndex = 0;
video.prototype.checkSegmentArray = function () {
var videoS = this;
if (videoS.segmentArray.length > 0 && !videoS.sourceBuffer.updating) {
var thevideo = videoS.segmentArray.shift();
videoS.sourceBuffer.appendBuffer(thevideo);
console.log("adding segment called"+videoS.addingSegmentIndex +" times");
console.log(thevideo);
videoS.addingSegmentIndex++;
}
console.log(videoS.videoPlayer.readyState);
console.log(videoS.sourceBuffer);
console.log(videoS.segmentArray.length + " items left");
console.log(videoS.sourceBuffer.updating);
console.log(videoS.source.readyState);
console.log("from checkSegmentArray");
console.log("\n");
}
video.prototype.playSegment = function (url, range) {
console.log("it happend again");
var videoSelf = this;
var httprequest = new XMLHttpRequest();
httprequest.open("GET", "PressPause/Media/videomp4", true);
httprequest.setRequestHeader("Range", "bytes=" + range);
httprequest.responseType = "arrayBuffer";
httprequest.send();
httprequest.onreadystatechange=function(e) {
if (this.readyState == 4) {
if (this.status == 200) {
videoSelf.segmentArray.push(new Uint8Array(httprequest.response));
videoSelf.checkSegmentArray.call(videoSelf);
}
}
}
};
video.prototype.processRange= function(range) {
var rangeArray = range.toString().split("-");
var first = rangeArray[0];
var second = rangeArray[1];
console.log("first: " + first, "second " + second);
}
video.prototype.init = function () {
console.log("calling mpd");
if (this.startInit==false) {
this.fetchMpd("video");
}
}
the new mpd generated using ffmpeg how can i process it in javascript what should i be looking for
<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:mpeg:DASH:schema:MPD:2011" xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011" type="static" mediaPresentationDuration="PT110.2S" minBufferTime="PT1S" profiles="urn:webm:dash:profile:webm-on-demand:2012">
<Period id="0" start="PT0S" duration="PT110.2S">
<AdaptationSet id="0" mimeType="video/webm" codecs="vp8" lang="eng" width="1280" height="720" bitstreamSwitching="true" subsegmentAlignment="true" subsegmentStartsWithSAP="1">
<Representation id="0" bandwidth="134033">
<BaseURL>C:\Users\solo\newfilemuxer.webm</BaseURL>
<SegmentBase indexRange="1223146-1223345">
<Initialization range="0-249"/>
</SegmentBase>
</Representation>
</AdaptationSet>
</Period>
You should take the codec attribute information of the MPD, maybe that's an issue. Does your content play when you append the segments directly to the source buffer? Can you also post your MPD with access to the content? Does the content play using the dash.js or bitdash MPEG-DASH players?

Values returned from image.onload(function() are 0 or undefined?

I try to get height/width from some background images, but how to get these values into some variables?
var bgobj = jQuery(this); // assigning the object
var url = bgobj.css('background-image').replace(/url\(|\)$|"/ig, '');
var img = new Image();
img.src = url;
Option 1:
alert('img.width: ' + img.width); // alert: " img.width: 0 "
Probably, the image hasn't loaded. So I try onload:
Option 2:
jQuery(bgimg).on('load', function() {
height = jQuery(bgimg).height();
//alert('height ' + height); //'480px' which is correct!
});
No way to get the value out for further use!? So I try callback:
Option 3:
var imageSize = function(url, callback) {
var img = new Image();
img.onload = function(){
var response = {};
var img = new Image();
img.onload = function() {
var x = img.width;
var y = img.height;
var z = y/x;
response = {width:x,height:y};
if(callback) callback(response);
}
img.src = url;
}
img.onload();
}
var getSize = function(url, callback) {
imageSize(url, function(response) {
var dim = response;
})
callback(dim);
}
var h;
imageSize(img.src, function(response) {
h=response.height;
//alert(h); // 800px (OK))
})
//alert(h); //undefined
//alert(imageSize.height); //undefined
//alert(imageSize.h); //undefined
//alert(imageSize.response.h); //undefined
Still no way to get the value into an ordinary variable.
Where did I go wrong?
You've overcomplicated it, but option 3 is one way to do it.
var imageSize = function(url, callback) {
var img = new Image();
img.onload = function(){
if(callback) callback(img.width,img.height);
}
img.src = url;
}
$(function(){
var url = $('#foo').css('background-image').replace(/url\(|\)$|"/ig, '');
imageSize(url,function(w,h){
alert("width=" + w + ", height=" + h);
})
});
#foo{
background-image:url(http://lorempixel.com/100/100/)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">test</div>
The thing to remember is that the method imageSize is asynchronous, so you must pass it a callback which will be called when the image has loaded. You cant have another method where you treat it as a synchronous call, that just wont work.

Categories

Resources