===== Comprobar si la imagen existe =====
puesto en un return:
var image = new Image();
image.onload = function() {
// image exists and is loaded
document.body.appendChild(image);
}
image.onerror = function() {
// image did not load
var err = new Image();
err.src = '/error.png';
document.body.appendChild(err);
}
image.src = "../imgs/6.jpg";
getInitialState: function(event) {
return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
return (
;
);
}
usando fetch:
fetch('https://via.placeholder.com/150', { method: 'HEAD' })
.then(res => {
if (res.ok) {
console.log('Image exists.');
} else {
console.log('Image does not exist.');
}
}).catch(err => console.log('Error:', err));
* [[https://attacomsian.com/blog/javascript-fetch-api]]
const getImageOrFallback = (path, fallback) => {
return new Promise(resolve => {
const img = new Image();
img.src = path;
img.onload = () => resolve(path);
img.onerror = () => resolve(fallback);
});
};
// Usage:
const link = getImageOrFallback(
'https://www.fillmurray.com/640/360',
'https://via.placeholder.com/150'
).then(result => console.log(result) || result)
* [[https://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript]]
* [[https://living-sun.com/es/jquery/516318-how-to-check-if-image-exists-with-given-url-jquery.html]]
El que me funciono:
let CargarLogoEmpresa = function(variable){
var image = new Image();
var url_image = variable;
image.src = url_image;
if (image.width == 0) {
return 'libs/img/logo/SinLogo.jpg';
} else {
return url_image;
}
}
===== Validando una imagen =====
function validarImagen(obj){
var uploadFile = obj.files[0];
if (!window.FileReader) {
alert('El navegador no soporta la lectura de archivos');
return;
}
if (!(/\.(jpg|png|gif)$/i).test(uploadFile.name)) {
alert('El archivo a adjuntar no es una imagen');
}
else {
var img = new Image();
img.onload = function () {
if (this.width.toFixed(0) != 200 && this.height.toFixed(0) != 200) {
alert('Las medidas deben ser: 200 * 200');
}
else if (uploadFile.size > 20000)
{
alert('El peso de la imagen no puede exceder los 200kb')
}
else {
alert('Imagen correcta :)')
}
};
img.src = URL.createObjectURL(uploadFile);
}
}
* [[https://anexsoft.com/validando-una-imagen-con-javascript]]