How can I apply a watermark in images using JavaScript? - javascript

I'm using angularJS and need to apply a watermark programatelly in images by calling an JS function. What I have is:
<figure><img class="watermark" ng-src="{{applyWatermark(img.url)}}"></figure>
So, I need to call that function applyWatermark (not implemented yet) and return a img with the watermark, but I'm not sure how can I build this function. Should it return the image? Can someone provide me some example how can I do this?
EDIT:
I did this, but it's not working:
$(function applyWatermark(image) {
watermark([image, 'watermark.png'])
.image(watermark.image.lowerRight())
.then(function (img) {
return img
});
})
Any idea?

Using watermark.js:
watermark(['/img/forest.jpg', '/img/logo.png'])
.image(watermark.image.lowerRight(0.5)) // Or lowerRight() for no opacity
.then(function (img) {
document.getElementById('alpha-image').appendChild(img);
});
If this doesn't work for you, maybe try this:
$.ajax({
url: 'http://www.example.com/your-image.jpg',
type: 'HEAD',
error: function() {
// File isn't found
},
success: function() {
// File is found! Do the watermarkage.
}
});
to test if the image exists before processing.

Related

How to reinitialize a dropzone element

I want to use dropzone to display thumbnails of images that I already have on the server. I am creating a CMS for a property website. The server has images associated with Sites of properties. When the page loads, the init function of my dropzone displays the relevant image for a given site as a thumbnail in the dropzone.
There is a drop down box on the page which lets the user select another site. When they do this I want the dropbox object to basically do what's in the init function again. Make a call to the server and display the thumbnails that are associated with this different site.
I haven't been able to get a solution yet (obviously). Typically I will get something like, "dropzone still attached" with stuff I have tried. I can't seem to see anything in the docs that is useful.
Any help would be appreciated :)
//my dropzone object
var myDropzone = $('#featured-development-dropzone').dropzone({
url: '#Url.Action("SaveFeaturedDevelopmentImage","Homepage")',
maxFiles: 1,
addRemoveLinks: true,
init: function () {
var myDropzone = this;
$("select").on('click', function () {
myDropzone.removeAllFiles(true);
});
var siteID = $('#siteDropdown').find(':selected').val();
$.ajax({
url: '#Url.Action("GetFeaturedDevelopmentImage", "Homepage")',
data: { siteID: siteID },
type: 'GET',
success: function (data) {
console.log(data);
if (data.data != null) {
var mockFile = {
name: data.filename,
size: data.fileSize
};
// Call the default addedfile event handler
myDropzone.emit("addedfile", mockFile);
console.log(typeof (data));
// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, "data:image/png;base64," + _arrayBufferToBase64(data.data));
myDropzone.emit("complete", mockFile);
}
}
});
this.on("sending", function (file, xhr, formData) {
formData.append("SiteID", siteID);
formData.append("imageTypeID", 4);
console.log(formData);
});
}
});
var prevSiteID;
$("select").on('click', function () {
prevSiteID = this.value;
}).change(function () {
var newSIteID = this.value;
// potentially put code here that will reinitialize the dropbox and display images associated with different site.
console.log(prevSiteID);
console.log(newSIteID);
changeFeaturedDevelopment(prevSiteID, newSIteID);
I belive you need to recall that function again. Since when you are triying to attach a new image, the dropzone zone is already defined in the page load. Or you call the init again or try to reset it, so the dropzone can reattach another image.

Ajax Loading graphic while waiting for d3 graphs/.json response? (Rails)

I am loading multiple d3 line graphs in a Ruby on Rails app and want to display a loading image (gif) while I wait for my data response to populate them.
What's the best, easiest way to do this? Should I place some jQuery inside my Ajax call or before it, perhaps?
I send a ajax request for some .json and draw the graphs in a .js file that looks like this:
my_d3_file.js:
var loadData = function () {
var path = window.location.pathname.split('/');
var site_id = path[path.length - 1];
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: '/data_reports.json?site_id=' + site_id + '&graphable=true',
dataType: 'json',
success: function (data) {
drawGraphs(data)
},
failure: function (result) {
error();
}
});
function drawGraphs(data) {
var svg = d3.select("#plot1").append("svg")...
// etc, code for d3 graphs
}
$(document).ready(function () {
loadData();
})
My html looks like this:
my_graphs.html.erb
<div id="plot1" class="plot"></div>
My Rails file structure looks like this:
assets
images
my_loading_image.gif
javascripts
my_d3_file.js
stylesheets
my_css.css
views
graph_folder
my_graphs.html.erb
Does something like this get me started? I'm just not sure where everything needs to be placed, specifically in my JavaScript file, in relation to the ajax call.
Inside ("#plot1"):
<img src="../../assets/images/ajax-loader.gif" id="loading-gif"
style="display:none" />
//also, is my file path correct?
In my css:
#loading-indicator {
position: relative;
left: 10px;
top: 10px;
}
In my_d3_file.js:
$(document).ajaxSend(function(event, request, settings) {
$('#loading-gif').show();
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-gif').hide();
});
Thanks so much! Let me know if I can provide more info!
Just include the spinner graphic inside the #plot1 tag
<div id="plot1" class="plot">
<img src="../../assets/images/ajax-loader.gif"/>
</div>
At the time you want to draw your graph here just select the image and remove it, and create an svg tag instead
d3.select("#plot1 img").remove();
var svg = d3.select("#plot1").append("svg")
.attr("width", 500)
.attr("height", 500);
Just add your drawing to this svg variable
Maybe this helps, in your ajax call use the beforeSend callback to display the loading gif, and in your success callback hide them and render the graphs. Something like:
$.ajax({
beforeSend. function() {
aFunctionToShowLoadingGIF();
},
success: function (data) {
aFunctionToHideTheLoadingGIF();
drawGraphs(data);
}
failure: function (result) {
error();
}
});
Just create a div with loader. Don't initially hide it.
<div id='loader'><img src="images/loader.gif"/></div>
Then hide the loader once the data is loaded by d3.
// load the d3 data
d3.json("json/data.json", function(treeData) {
$("#loader").hide();
//rest of code
}
Show the loader div again if you need to reload the data elsewhere.

How to load images from a directory using jquery

I am toying with the following code trying to take images from a set directory, and preload them. I do not want to load the images into a div, but rather preload them in the memory using the normal:
new Image().src = "/wp-content/themes/NCHERM_Theme/images/home4-events.jpg";
I am rather new to jquery so looking for some help to finalize this:
window.onload = function($) {
var folder = "images/preload";
$.ajax({
url : folder,
success: function (data) {
//go through each item in folder
$.each(data, function(i,filename) {
//take each item and run into the normal preload method
setTimeout(function() {
// preload images
new Image().src = filename;
}, 1000);
});
}
});
};
running this in wordpress I get `403 forbbiden' on the url for the folder before i can even test if this is working
Make sure you have added reference of JQuery inside your <script> tag. JQuery Library is missing.
<script src="../../jquery.min.js" type="text/javascript"></script>
For your reference: $.ajax is not a function
Try this code if it work for you.
window.onload = function($) {
var folder = "images/preload";
$.ajax({
url : folder,
success: function (data) {
//go through each item in folder
$.each(data, function(i,filename) {
//take each item and run into the normal preload method
setTimeout(function() {
// preload images
var $img=$("<img />",{"src":filename});
$('#target_id').append($img);
}, 1000);
});
}
});
};
You can solve 403 error by adding:
Options +Indexes
On .htaccess file.

Javascript jQuery How to load default image if

I wanted to load the default image if the user's one didn't exist. I tried this but it didn't work.
$('#avatar').load(function(){
// ... loaded
}).error(function(){
// ... not loaded
$(this).attr('src','/images2/no-avatar2.png');
});
Anyone know how I could do this?
Someone uses this:
function loadDefault(f, ff) {
img = document.getElementById(f);
if(!img.complete) {
img.src = ff;
}
if(typeof(img.naturalWidth) != "undefined" && img.naturalWidth == 0) {
img.src = ff;
}
}
function init() {
setTimeout("loadDefault('side_avatar', '/images/default/avatar_player_profile.gif')", 100);
setTimeout("imageResize(740)", 100);
tooltip = new ToolTip();
tooltip.init('hoverBox', 'loading...');
}
How could I use something like this?
It looks like you are missing your load url as the first parameter of the load() function. Also, without seeing your HTML, I'll assume #avatar is an img tag the way you are using it in the error function. I don't think you can load HTML into an img so you may be better off structuring your html and js like so:
HTML Example:
<div id="avatarDiv">
<img id="avatar" src="" alt="" />
</div>
JS Example:
$('#avatarDiv').load('avatar.php', function() {
// ... loaded
}).error(function() {
// ... not loaded
$('img#avatar').attr('src','/images2/no-avatar2.png');
});
Then just make sure your avatar.php file returns the full html of the image object:
<img id="avatar" src="successful-avatar.jpg" alt="" />
Docs: http://api.jquery.com/load/
I'd try something like this:
$.get("get-avatar.php", function(response) {
$("#avatar").attr('src', response);
}).error(function(response) {
$(this).attr('src', '/images2/no-avatar2.png');
})
as long as avatar.php returns a http error message if the image doesn't exist.
This routine uses ajax to see if the image file exists:
HTML:
<img id='avatar' src='/images2/avatar2find.png' alt='No Image Available'></img>
Script:
$(window).load(function() {
var $img = $('#avatar');
$.ajax({
url: $img.attr('src'),
type: 'get',
statusCode: {
404: function() {
$img.attr('src', '/images2/no-avatar2.png');
}
},
error:
function() {
// do something?
}
});
});

What is the easiest/best way to show that an HTML element is AJAX Loading?

Sometimes in my application there are many elements loading so I want to show the typical AJAX spinner above the control (or DOM node) with it disabled.
What is the easiest/best way to do that?
Ideally I would like to:
$("#myelement").loading();
$("#myelement").finishloading();
Or even better being able to do AJAX requests directly with the element:
$("#myelement").post(url, params, myfunction);
Being #myelement a regular node or form input.
You could use beforeSend and complete callbacks:
$.ajax({
url: 'script.cgi',
type: 'POST',
beforeSend: function() {
$('.spinner').show();
},
complete: function() {
// will trigger even if request fails
$('.spinner').hide();
},
success: function(result) {
// todo: do something with the result
}
});
Since you're already using jQuery, you may want to look into BlockUI in conjunction with Darin Dimitrov's answer. I haven't used it yet myself as I just came across this today, but it looks decent.
If you're writing a semi-large-ish application and anticipate making many AJAX calls from different places in your code, I would suggest that you either add a layer of abstraction over $.ajax, or create a helper function to avoid having boiler plate for your UI indicator all over the place. This will help you out a lot should you ever need to change your indicator.
Abstraction method
var ajax = function(options) {
$.ajax($.extend(
{
beforeSend: function() {
$.blockUI();
},
complete: function() {
$.unblockUI();
}
},
options
));
};
ajax({
url: 'script.cgi',
type: 'POST',
success: function(result) {
// todo: do something with the result
});
Helper method
var ajaxSettings = function(options) {
return $.extend(
{
beforeSend: function() {
$.blockUI();
},
complete: function() {
$.unblockUI();
}
},
options
);
};
$.ajax(ajaxSettings({
url: 'script.cgi',
type: 'POST',
success: function(result) {
// todo: do something with the result
}
}));
Also, I wouldn't suggest overwriting the $.ajax method itself.
what i've done in the past is, on post pass the element id (a containing div) to a function which replaces it's inner HTML with a loading image, and then in the post back replace it's content again with the updated real content.
If you want to show the spinner every when an ajax call is in progress I think you should use ajaxStart and ajaxStop.
$("#spinner")
.ajaxStart(function(){$(this).show();})
.ajaxStop(function(){$(this).hide();});

Categories