Random image in Google slides - google-slides

How could I insert a random image into Google Slides? like if I use a link, that always leads to a random image, to where I don't even know what the image will be once I present. -Thanks
(This link can be used to go to a random picture: https://source.unsplash.com/random/300x200)

As #Tanaike commented you cannot access a resource that needs authorization using Simple Triggers.
They cannot access services that require authorization.
onOpen(e) Simple Trigger pointing to "https://www.googleapis.com/auth/script.external_request" scope in this case
As a workaround you could change the images every day, using a Time Driven Installable Trigger.
Code.gs
function changeImage() {
let slideP = SlidesApp.getActivePresentation()
let slide1 = slideP.getSlides()[0]
let img = slide1.getImages()[0]
// Fetch a new image
let req = UrlFetchApp.fetch('https://source.unsplash.com/random/300x200')
let blobImage = req.getAs('image/jpeg')
// Get the properties of the actual image
let [left, top, width, height] = [
img.getLeft(),
img.getTop(),
img.getWidth(),
img.getHeight()
]
// Remove the old one
img.remove()
// Add the new one with the same attributes
slide1.insertImage(blobImage, left, top, width, height)
}
Then simply add the function to a Trigger.

Related

How to load a local image to WebGL context

I was trying Azure maps Symbol feature. I wanted to add a custom image as symbol.
When i used path of local image, it was not working.
"All resources, such as icon images, must be loaded into the WebGL context."
Please help me how to make local image to be loaded as webGL context.
You must add your image to the maps image sprite before you the symbol layer can use it. You would pass the URL and a unique name for the image into the map.imageSprite.add function. This is a Promise that you have to wait for as the image is loaded asynchronously. Once loaded, you can then set the image option of the symbol layers iconOptions to the unique name of the image.
Some additional code samples can be found here: https://samples.azuremaps.com/?sample=custom-symbol-image-icon
Update:
Here is a code block show how to add an image to the maps image sprite (WebGL context).
//Wait until the map resources are ready.
map.events.add('ready', function () {
//Create a data source and add it to the map.
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
//Load the custom image icon into the map resources.
map.imageSprite.add('my-custom-icon', '/images/icons/showers.png').then(function () {
//Add a layer for rendering point data as symbols.
map.layers.add(new atlas.layer.SymbolLayer(datasource, null, {
iconOptions: {
//Pass in the id of the custom icon that was loaded into the map resources.
image: 'my-custom-icon'
}
}));
});
});
If you have multiple images you want to use, you can create an array of the imade add promises, then use Promise.all. Here is a good code sample: https://samples.azuremaps.com/?sample=data-driven-symbol-icons And here is a simply code block example:
//Wait until the map resources are ready.
map.events.add('ready', function () {
//Create a data source and add it to the map.
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
//Create an array of custom icon promises to load into the map.
var iconPromises = [
map.imageSprite.add('gas_station_icon', '/images/icons/gas_station_pin.png'),
map.imageSprite.add('grocery_store_icon', '/images/icons/grocery_cart_pin.png'),
map.imageSprite.add('restaurant_icon', '/images/icons/restaurant_pin.png'),
map.imageSprite.add('school_icon', '/images/icons/school_pin.png'),
];
//Load all the custom image icons into the map resources.
Promise.all(iconPromises).then(function () {
//Add a layer for rendering point data as symbols.
map.layers.add(new atlas.layer.SymbolLayer(datasource, null, {
iconOptions: {
//Use a data driven expression based on properties in the features to determine which image to use for each feature.
image: [
'match',
//In this example each feature has a "EntityType" property that we use to select the appropriate icon.
['get', 'EntityType'],
//For each entity type, specify the icon name to use.
'Gas Station', 'gas_station_icon',
'Grocery Store', 'grocery_store_icon',
'Restaurant', 'restaurant_icon',
'School', 'school_icon',
//Default fallback icon.
'marker-blue'
]
}
}));
});
Can you provide us your code?
I've tried to add local file as image to Azure Maps symbol layer. See examples here: click.
Local file file:///D:/showers.png failed with error: URL scheme must be "http" or "https" for CORS request., but same file on localhost server worked well:
P.S. Maybe I do not clearly understand the problem?

Wordpress - Changing Background-Color of Multiple Divs

I have multiple DIV elements on my page with the class "grid-item-container"
I want to make the background-color of each one different. I will set an array of 5 different colours that can be set.
There is a script available here that seems to do this: http://jsfiddle.net/VXG36/1/
$(document).ready(function() {
var randomColors = ["green","yellow","red","blue","orange","pink","cyan"];
$(".random").each(function(index) {
var len = randomColors.length;
var randomNum = Math.floor(Math.random()*len);
$(this).css("backgroundColor",randomColors[randomNum]);
//Removes color from array so it can't be used again
randomColors.splice(randomNum, 1);
});
});
I cannot however get it to run on my page. Is there something in this script that needs to be amended to make it Wordpress friendly?
Kind regards
Dave
You might wan't to wrap it in something like this:
jQuery(document).ready(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
});
The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link. Read more about it in Codex here.
Also, change $(.random) to $(.grid-item-container), this targets the class of your div.

Custom image size in new media uploader

I am developing a relatively simple Wordpress plugin for a client. It is used to upload/select images which are then saved (as image path) in the option variables and used as full-background images for the website's different categories/pages/etc..
Since images are of "wallpapery nature" (i.e. big) I added a custom image size with a maximum width of 1920 pixels (height is set to "auto", i.e. no image cropping). And that part also works, upon upload, images are being resized to my custom 1920 px width.
Now, the thing is, for uploading/choosing the background image I'm using the new media uploader and it works except that the chosen image (path) is always for the original uploaded image, for example "my-background-image.jpg".
My question is: is there a way to enable users (or make the uploader do it automatically) to select the 1920 px sized version of the original image, for example "my-background-image-1920x1080.jpg"?
Thanks!
I managed to sort out my problem, a bit differently than I first approached it - but it is a solution I'm even more pleased.
So, when you use the new media uploader, you have a jquery code that looks something like this:
jQuery(document).ready(function($){
var custom_uploader;
$('.upload_image_button').unbind('click').click(function(e) {
e.preventDefault();
formfieldID=jQuery(this).prev().attr("id");
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$('.' + formfieldID).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
Now, note the part of the code that gets the selected file's url:
$('.' + formfieldID).val(attachment.url);
This gets the ORIGINAL attachment's (image) url. So, to get some other image size, like thumbnail, large, etc. you use this:
$('.' + formfieldID).val(attachment.sizes.thumbnail.url);
AND in the end, you can even use your own custom image size like this:
$('.' + formfieldID).val(attachment.sizes.mysize.url);
BUT... I ran into one stupid but very time-consuming problem: DO NOT give your custom image size a name that is separated by a minus sign, like "background-image"; because while Wordpress part of it will work (the new image size will be visible and usable) the jquery for media uploader won't work with it.
If you need a separator, use underscore instead, e.g. "background_image" and it will work normally! This could be a beginner's error on my part, but I thought it could save someone some time! :)

Best way to retrieve image from server using ajax [duplicate]

Is it possible to reload an image with an identical file name from a server using jQuery?
For example, I have an image on a page, however, the physical image can change based on user actions. Note, this does not mean the file name changes, but the actual file itself.
ie:
User views image on default page
User uploads new image
Default image on page does not change(I assume this is due to the file name being identical, the browser uses the cached version)
Regardless of how often the code below is called, the same issue persists.
$("#myimg").attr("src", "/myimg.jpg");
In the jQuery documentation, the "load" function would be perfect if it had a default method of firing the event as opposed to binding a callback function to a successful/complete load of an element.
Any assistance is greatly appreciated.
It sounds like it's your browser caching the image (which I now notice you wrote in your question). You can force the browser to reload the image by passing an extra variable like so:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
It's probably not the best way, but I've solved this problem in the past by simply appending a timestamp to the image URL using JavaScript:
$("#myimg").attr("src", "/myimg.jpg?timestamp=" + new Date().getTime());
Next time it loads, the timestamp is set to the current time and the URL is different, so the browser does a GET for the image instead of using the cached version.
This could be one of the two problems you mention yourself.
The server is caching the image
The jQuery does not fire or at least doesn't update the attribute
To be honest, I think it's number two. Would be a lot easier if we could see some more jQuery. But for a start, try remove the attribute first, and then set it again. Just to see if that helps:
$("#myimg").removeAttr("src").attr("src", "/myimg.jpg");
Even if this works, post some code since this is not optimal, imo :-)
with one line with no worries about hardcoding the image src into the javascript (thanks to jeerose for the ideas:
$("#myimg").attr("src", $("#myimg").attr("src")+"?timestamp=" + new Date().getTime());
To bypass caching and avoid adding infinite timestamps to the image url, strip the previous timestamp before adding a new one, this is how I've done it.
//refresh the image every 60seconds
var xyro_refresh_timer = setInterval(xyro_refresh_function, 60000);
function xyro_refresh_function(){
//refreshes an image with a .xyro_refresh class regardless of caching
//get the src attribute
source = jQuery(".xyro_refresh").attr("src");
//remove previously added timestamps
source = source.split("?", 1);//turns "image.jpg?timestamp=1234" into "image.jpg" avoiding infinitely adding new timestamps
//prep new src attribute by adding a timestamp
new_source = source + "?timestamp=" + new Date().getTime();
//alert(new_source); //you may want to alert that during developement to see if you're getting what you wanted
//set the new src attribute
jQuery(".xyro_refresh").attr("src", new_source);
}
This works great! however if you reload the src multiple times, the timestamp gets concatenated to the url too. I've modified the accepted answer to deal with that.
$('#image_reload_button').on('click', function () {
var img = $('#your_image_selector');
var src = img.attr('src');
var i = src.indexOf('?dummy=');
src = i != -1 ? src.substring(0, i) : src;
var d = new Date();
img.attr('src', src + '?dummy=' + d.getTime());
});
Have you tried resetting the image containers html. Of course if it's the browser that is caching then this wouldn't help.
function imageUploadComplete () {
$("#image_container").html("<img src='" + newImageUrl + "'>");
}
Some times actually solution like -
$("#Image").attr("src", $('#srcVal').val()+"&"+Math.floor(Math.random()*1000));
also not refresh src properly, try out this, it worked for me ->
$("#Image").attr("src", "dummy.jpg");
$("#Image").attr("src", $('#srcVal').val()+"&"+Math.floor(Math.random()*1000));
Using "#" as a delimiter might be useful
My images are kept in a "hidden" folder above "www" so that only logged users are allowed access to them. For this reason I cannot use the ordinary <img src=/somefolder/1023.jpg> but I send requests to the server like <img src=?1023> and it responds by sending back the image kept under name '1023'.
The application is used for image cropping, so after an ajax request to crop the image, it is changed as content on the server but keeps its original name. In order to see the result of the cropping, after the ajax request has been completed, the first image is removed from the DOM and a new image is inserted with the same name <img src=?1023>.
To avoid cashing I add to the request the "time" tag prepended with "#" so it becomes like <img src=?1023#1467294764124>. The server automatically filters out the hash part of the request and responds correctly by sending back my image kept as '1023'. Thus I always get the last version of the image without much server-side decoding.
Based on #kasper Taeymans' answer.
If u simply need reload image (not replace it's src with smth new), try:
$(function() {
var img = $('#img');
var refreshImg = function(img) {
// the core of answer is 2 lines below
var dummy = '?dummy=';
img.attr('src', img.attr('src').split(dummy)[0] + dummy + (new Date()).getTime());
// remove call on production
updateImgVisualizer();
};
// for display current img url in input
// for sandbox only!
var updateImgVisualizer = function() {
$('#img-url').val(img.attr('src'));
};
// bind img reload on btn click
$('.img-reloader').click(function() {
refreshImg(img);
});
// remove call on production
updateImgVisualizer();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="img" src="http://dummyimage.com/628x150/">
<p>
<label>
Current url of img:
<input id="img-url" type="text" readonly style="width:500px">
</label>
</p>
<p>
<button class="img-reloader">Refresh</button>
</p>
I may have to reload the image source several times. I found a solution with Lodash that works well for me:
$("#myimg").attr('src', _.split($("#myimg").attr('src'), '?', 1)[0] + '?t=' + _.now());
An existing timestamp will be truncated and replaced with a new one.
If you need a refresh of the exact URL and your browser has the image cached, you can use AJAX and a request header to force your browser to download a new copy (even if it isn't stale yet). Here's how you'd do that:
var img = $("#myimg");
var url = img.attr("src");
$.ajax({
url: url,
headers: { "Cache-Control": "no-cache" }
}).done(function(){
// Refresh is complete, assign the image again
img.attr("src", url);
});
Nothing else worked for me because while appending a token to the query string would download the new image, it didn't invalidate the image in the cache at the old URL so future requests would continue to show the old image. The old URL is the only one sent to the browser, and the server was directing the client to cache the image for longer than it should.
If this still doesn't refresh the image for you, see if this answer helps. For more information, here is documentation on the Cache-Control request header.
In the html:
foreach (var item in images) {
<Img src="#Url.Content(item.ImageUrl+"?"+DateTime.Now)" >
}
I simply do this in html:
<script>
$(document).load(function () {
d = new Date();
$('#<%= imgpreview.ClientID %>').attr('src','');
});
</script>
And reload the image in code behind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
image.Src = "/image.jpg"; //url caming from database
}
}

Can I enable users on Plone4 to show/hide the Portlet column on-the-fly

The Portlets in Plone are quite handy but I'd like to be able to provide some method to users to be able to temporarily hide/show the portlets column. That is, by clicking a button, the portlets column should collapse and you see the content page in full width. Then clicking again and the portlets panel on the left expands and the main content page width shrinks to accommodate.
I've observed the HTML ID of the portlets column is "portal-column-one" and I tried adding a button to the page that runs javascript to set the visibility property of that element to "hidden" but this seemed to have no effect. I was able to go into Firebug and add style="visibility:hidden;" to the "portal-column-one" element and it had the effect of making the region invisible w/o resizing the page.
I am using Plone 4.1. I have the site configured with navigation portlet on all pages except the main page which has Navigation, Review List and Recent Changes.
So it seems it must be possible to embed some javascript in the page (I was thinking of adding this to the plone.logo page which I've already customized). But I guess its more complicated than the few stabs I've made at it.
Thanks in advance for any advice.
Solution (Thanks to input from Ulrich Schwarz and hvelarde):
The solution I arrived at uses JavaScript to set CSS attributes to show/hide the Portlets Column (Left side) and expand the content column to fill the space the porlets column filled.
I started by customizing the Plone header template to add a link for the user to toggle the view of the Porlets column. I also put the necessary javascript functions in this header.
To customize the header, go to the following page (need to be logged in as Admin of your Plone site):
http://SERVER/SITE/portal_view_customizations/zope.interface.interface-plone.logo
Where:
SERVER is the address and port of your site (e.g. localhost:8080)
SITE is the short name of your Plone Site
To create this page:
Go to Site Setup (as Admin)
Go to Zope Management Interface
Click on "portal_view_customizations"
Click on "plone.logo" (or at least this is where I choose to put the button so it would be located just above the navigation Portlet)
Add the following to the page:
<script>
function getById(id) {
return document.getElementById(id);
}
function TogglePortletsPanel() {
var dispVal = getById('portal-column-one').style.display
if( dispVal == "none") { // Normal display
SetPortletsPanelState("inline");
} else { // Full Screen Content
SetPortletsPanelState("none");
}
}
function SetPortletsPanelState(dispVal) {
var nav = getById('portal-column-one');
var content = getById('portal-column-content');
if( dispVal == "none") { // Normal display
nav.style.display='none';
content.className='cell width-full position-0';
// Set cookie to updated value
setCookie("portletDisplayState","none",365);
} else { // Full Screen Content
nav.style.display='inline';
content.className='cell width-3:4 position-1:4';
// Set cookie to updated value
setCookie("portletDisplayState","inline",365);
}
}
function InitializePortletsPanelState() {
var portletDisplayState=getCookie("portletDisplayState");
//alert("portletDisplayState="+portletDisplayState)
if (portletDisplayState!=null) SetPortletsPanelState(portletDisplayState);
}
function setCookie(c_name,value,exdays) {
//alert(c_name+"="+value);
// cookie format: document.cookie = 'name=value; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var exp= ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + escape(value) + exp + "; path=/";
}
function getCookie(c_name) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name) return unescape(y);
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {oldonload(); }
func();
}
}
}
addLoadEvent(InitializePortletsPanelState);
</script>
<a style="font-size:50%;" href="javascript:TogglePortletsPanel();">Toggle Portlets Panel</a>
6. Save the page
Notes:
I got the names of the plone div elements using Firebug.
I also used Firebug to experiment with different settings to speed up prototyping. For example, editing the HTML inline to verify settings do as expected.
There is a slight but of delay until the Left Portlet panel is hidden. This is only obvious on Safari for me (which is probably due to how fast it is) but not on Firefox or IE.
Maybe it's just a matter of setting the right property: you want display:none, not visibility:hidden.
But even then, the content area will probably not reflow automatically, you'll need to (dynamically) change the class on it as well.
Specifically, you'll need to put classes width-full and position-0 on portal-column-content, instead of width-1:2 and position-1:4.
This must be achieved client side by javascript (jquery).
You must first read documentation about the css grid framework used by plone: deco.gs. The website is down so, git clone this repo: https://github.com/limi/deco.gs and open pages in a webbrowser
Note: you just have to change css classes on the containers.
Try adi.fullscreen, it respects Plone's css-structure as Ulrich Schwarz thoughtfully mentioned.

Resources