Change image size on click of button in jQuery - php

I am working on image upload and I need to add functionality for image shapes.
There are buttons for landscape, portrait, square and panoramic. When the user clicks any of these, the div shape will change accordingly.
This is the code for the square shape but when I click on the square shape, it stretches the image. I want to change the shape of the div without stretching the image.
$('#Square').on('click', function(){
var images = $("#uploadedImage");
for(i=0; i<images.length; i++)
images[i].onload = centerImage(images[i]);
function centerImage(img) {
if (img.width > img.height ) {
var y = 160;
var x = img.width/img.height*y;
var marx = (x-y)/2;
img.style.height = y+"px";
img.style.marginLeft = -(marx) + "px";
}
}
});

It's difficult to recreate running example without more generalized code, but your function clearly changes the dimensions of variable img, the image passed in to the function, and not any div or other element besides the image that was clicked. If you want to change a div based on the same HxW test of the image, change the img.* parts of your function to $('#DivYouWant').* and you should get on the right track. Something along the lines of:
function centerImage(img) {
if (img.width > img.height ) {
var y = 160;
var x = img.width/img.height*y;
var marx = (x-y)/2;
$('#DivYouWannaMod').height = y+"px";
$('#DivYouWannaMod').marginLeft = -(marx) + "px";
}
}

Related

Filling D3.js Pie Graph with SQL Query

I am currently using D3.js to make a pie graph. The data is stored in a MSSQL database, which is then converted to JSON using PHP. Here is my code that does that
<?php
// Server Name
$myServer = "SRVR";
// Database
$myDB = "TestDB";
// If using Windows Authentication, get rid of, "'UID'=>$myUser, 'PWD'=>$myPass, "
// Notice that the latest driver uses sqlsrv rather than mssql
$conn = sqlsrv_connect('Database'=>$myDB));
// Change TestDB.vwTestData to YOURDB.dbo.YOURTABLENAME
$sql = "SELECT col, SUM(num) AS 'value'
FROM db
GROUP BY col";
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
// This will output in JSON format if you try to hit the page in a browser
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
This works fine. I've tested it, and it outputs JSON in something like this:
[{"col":null,"value":247.9042254},{"col":"value1","value":16.8151576061},{"col":"value2","value":235.4833175609},{"col":"value3","value":2316.072432028},{"col":"value4","value":8904.4001532729}]
How can I put this in the graph? Here is my .js code
(function() {
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return // Something goes here I assume });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("scripts/graphs/script.php", function(error, data) {
data.forEach(function(d) {
// Something needs to go here?
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
});
})();
If someone could help me out, that would be great. Thanks!
I figured it out. I used this code and customized it for JSON
https://gist.github.com/enjalot/1203641
Here is what I got
(function() {
var w = 670, //width
h = 326, //height
r = 150, //radius
color = d3.scale.category20c(); //builtin range of colors
d3.json("script.php", function (data) {
var vis = d3.select("body")
.append("svg:svg") //create the SVG element inside the <body>
.data([data]) //associate our data with the document
.attr("width", w) //set the width and height of our visualization (these will be attributes of the <svg> tag
.attr("height", h)
.append("svg:g") //make a group to hold our pie chart
.attr("transform", "translate(" + r + "," + r + ")") //move the center of the pie chart from 0, 0 to radius, radius
var arc = d3.svg.arc() //this will create <path> elements for us using arc data
.outerRadius(r);
var pie = d3.layout.pie() //this will create arc data for us given a list of values
.value(function(d) { return d.value; }); //we must tell it out to access the value of each element in our data array
var arcs = vis.selectAll("g.slice") //this selects all <g> elements with class slice (there aren't any yet)
.data(pie) //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties)
.enter() //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
.append("svg:g") //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
.attr("class", "slice"); //allow us to style things in the slices (like text)
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } ) //set the color for each slice to be chosen from the color function defined above
.attr("d", arc); //this creates the actual SVG path using the associated data (pie) with the arc drawing function
arcs.append("svg:text") //add a label to each slice
.attr("transform", function(d) { //set the label's origin to the center of the arc
//we have to make sure to set these before calling arc.centroid
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")"; //this gives us a pair of coordinates like [50, 50]
})
.attr("text-anchor", "middle") //center the text on it's origin
.text(function(d, i) { return data[i].col; }); //get the label from our original data array
})
})();
So what was wrong was that I wasn't connecting the key values from the JSON, to the variables in the JS. Here are the lines to change:
var vis = d3.select("<PUT DIV ID HERE>")
.value(function(d) { return d.<PUT NUMBER VALUE KEY NAME HERE>; });
.text(function(d, i) { return data[i].<PUT SLICE CATEGORY HERE>; });
I am not entirely certain what is not working about your code, but you could try something simple like:
d3.json("scripts/graphs/script.php", function(error, data) {
data.forEach(function(d) {
d.value = +d.value
});
var g...
Alternately, could you just call the php script and store the returned json object in a variable, then pass that variable to d3.json?

Scroll through web images after thumbnail

I searched, but did not find the answer to this.
I have a website that displays hundreds of images in thumbnail format. I'm currently using php to display all of the images in thumbnail, then when the thumbnail is clicked upon to display the images in full-size.
What I would like to do is be able to click on a thumbnail and see the resulting full-size image, then at that point be able to scroll both back and forth through the full-size images without going back to the thumbnails.
As an added feature, when viewing the thumbnails, I would like to only load the ones that are currently displayed on the client page...ie - if the client screen resolution supports 20, then load only 20 and wait to load the rest on the client until the user scrolls down. The primary client in this use case is an iphone.
Thanks in advance!
you need to use a slider jquery plugin
Like
Jquery Light Box Plugin
When you click on the image, it should point to a new PHP file containing the full size image, or even better, load it in a new <div> with php you can get the client resolution with other tools
You actual have two seperate questions. One is to show the thumbs fullsize and be able to click to the next image. Almost every plugin to show images has that options. Personally i use fancybox, but pick anyone you like. To enable the next/prev buttons you need to group the images useing the rel tag.
Now to load the images per page, similar to google does it, you need to load it all in by javascript. Below is a setup of how you could do it. This is untested, as I did not have an image gallery at hand.
In the code below I load all images into the array at once, which is not perfect when you have a lot of images (like 1000+). In that case your better of using AJAX to load a new page. But if you have a smaller amount of images, this will be faster.
<script>
//simple JS class to store thumn and fullimage url
function MyImage(thumbnail, fullimage, imgtitle) {
this.thumb = thumbnail;
this.full = fullimage;
this.title = imgtitle;
}
//array that holds all the images
var imagesArray = new Array();
var currentImage = 0;
<?php
//use php code to loop trough your images and store them in the array
//query code to fetch images
//each row like $row['thumb'] and $row['full'] and $row['title'];
while ($row = mysqli_fetch_assoc($result))
{
echo "imagesArray.push(new MyImage('".$row['thumb']."', '".$row['full']."', '".$row['title']."'));";
}
?>
//the thumb width is the width of the full container incl. padding
//In this case I want to use 50x50 images and have 10px on the right and at the bottom. Which results in 60x60
var thumbWidth = 60;
var thumbHeight = 60;
var screenWidth = $('body').width();
var screenHeight = $('body').height();
var maxImagesPerRow = Math.round(screenWidth / thumbWidth);
var maxImagesPerCol = Math.round(screenHeight / thumbHeight);
var totalImagesPerPage = maxImagesPerRow * maxImagesPerCol;
//function to load a new page
//assuming you use jquery
function loadNextPage() {
var start = currentImage;
var end = currentImage + totalImagesPerPage;
if (end >= imagesArray.length) {
end = imagesArray.length - 1;
}
if (end<=start)
return; //last images loaded
$container = $('#thumbnailContainer'); //save to var for speed
$page = $('<div></div>'); //use a new container, not on stage, to prevent the dom for reloading everything on each iteration of the loop
for (start;start<=end;start++) {
//add a new thumbnail to the page
$page.append('<div style="margin:0;padding:0 10px 10px 0;"><a class="fancybox" rel="mygallery" href="'+imagesArray[start].full+'" title="'+imagesArray[start].title+'"><img src="'+imagesArray[start].thumb+'" alt="" /></a></div>');
}
currentImage = start;
//when all images are added to the page, add the page to the container.
$container.append($page);
}
$(function() {
//when loading ready, load the first page
loadNextPage();
});
//function to check if we need to load a new page
function checkScroll() {
var fromTop = $('body').scrollTop();
//page with a 1-based index
var page = 1 + Math.round(fromTop / screenHeight);
var loadedImages = page*totalImagesPerPage;
if (loadedImages==currentImage) {
//we are scrolling the last loaded page
//load a new page
loadNextPage();
}
}
window.onscroll = checkScroll;
</script>
<body>
<div id='thumbnailContainer'></div>
</body>

How to display multiple images on random?

i have this script i'm using to display random images with hyperlinks. can anyone tell me how i might adapt it to display 5 random images at once, preferably without repeating the same image twice?
Thanks
<script language="JavaScript">
<!--
/*
Random Image Link Script- By JavaScript Kit(http://www.javascriptkit.com)
Over 200+ free JavaScripts here!
Updated: 00/04/25
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="data/adverts/ad1.png"
myimages[2]="data/adverts/ad2.png"
myimages[3]="data/adverts/ad3.png"
myimages[4]="data/adverts/ad4.png"
myimages[5]="data/adverts/ad5.png"
//specify corresponding links below
var imagelinks=new Array()
imagelinks[1]="http://www.javascriptkit.com"
imagelinks[2]="http://www.netscape.com"
imagelinks[3]="http://www.microsoft.com"
imagelinks[4]="http://www.dynamicdrive.com"
imagelinks[5]="http://www.freewarejava.com"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}
random_imglink()
//-->
</script>
function random_imglink(){
var myimages=new Array();
...
var imagelinks=new Array();
...
var used = [];
var ry;
var howmany = 5;
for (var i = 1; i <= howmany; i++) {
ry=Math.ceil(Math.random()*myimages.length);
while(used.indexOf(ry)!=-1){
ry=Math.ceil(Math.random()*myimages.length);
}
used.push[ry];
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}
}
this assumes you're going to put more images in your array than 5.
Instead random and checking with while if you have already chosen an image you can move the choosen image to the end of the array and reduce the variable for the random by one. Example:
function random_imglink(select){
if (select > 5 ) {
// make it fail ...
}
//specify random images below. You can have as many as you wish
var myimages = new Array();
myimages[0]="data/adverts/ad1.png"
myimages[1]="data/adverts/ad2.png"
myimages[2]="data/adverts/ad3.png"
myimages[3]="data/adverts/ad4.png"
myimages[4]="data/adverts/ad5.png"
//specify corresponding links below
var imagelinks=new Array()
imagelinks[0]="http://www.javascriptkit.com"
imagelinks[1]="http://www.netscape.com"
imagelinks[2]="http://www.microsoft.com"
imagelinks[3]="http://www.dynamicdrive.com"
imagelinks[4]="http://www.freewarejava.com"
var size = myimages.length
for (var i=0;i<select;i++) {
var index = Math.floor(Math.random() * size);
document.write('<a href='+'"'+imagelinks[index]+'"'+'><img src="'+myimages[index]+'" border=0></a>');
var tmp = myimages[index];
myimages[index] = myimages[size - 1];
myimages[size - 1] = tmp;
tmp = imagelinks[index];
imagelinks[index] = imagelinks[size - 1];
imagelinks[size - 1] = tmp;
--size;
}
}
random_imglink(3);
It could be something like that in one line of code and without creating functions:
<img src="https://www.example.com/images/image-<?php echo rand(1,7); ?>.jpg">
In order to get this to work, you’ll want to name your images: image-1.jpg, image-2.jpg, image-3.jpg....image-7.jpg,
When the page loads, the PHP rand() will echo a random number (in this case, a number between 1 and 7), completing the URL and thus displaying the corresponding image. Source: https://jonbellah.com/load-random-images-with-php/

Dynamically set selection of jcrop (not fixed selection)

I am working with a jcrop now I want to do something like here
jQuery(function(){
jQuery(".image_container .a-center h2").html("Upload another picture")
var api;
jQuery('#cropbox').Jcrop({
bgOpacity: 0.5,
bgColor: 'black',
addClass: 'jcrop-dark',
aspectRatio: 320/180,
setSelect:[320,320,180,180],
onSelect: updateCoords,
onChange: updateCoords
},function(){
api = this;
api.setOptions({ bgFade: true });
api.ui.selection.addClass('jcrop-selection');
});
});
and it gives this kinda output on selection
and I want this kind of selection upon
what should I do to get max selection for width.
var ratio = 1.2222222;
var jcrop_api = $.Jcrop('#modal-file-crop-image');
jcrop_api.setOptions({ aspectRatio: ratio });
var dim = jcrop_api.getBounds();
dim should hold an array of the image size
so like [380,180]
i use the following to center the crop area based on aspect ratio
var $img = $("#modal-file-crop-image");
var w = $img.width();
var h = $img.height();
$img.css({"width": w, "height": h})
var ratio = 1.2222222;
var jcrop_api = $.Jcrop('#modal-file-crop-image');
jcrop_api.setOptions({ aspectRatio: ratio });
var dim = jcrop_api.getBounds();
var x = 0, y = 0, x_ = dim[0], y_ = dim[1];
var x_r = (x_ / ratio) - y_;
var y_r = (y_ / ratio) - x_;
if (x_r > 0) {
x = x_r / 2;
}
if (y_r > 0) {
y = y_r / 2;
}
jcrop_api.setSelect([x, y, dim[0], dim[1]]);
in your case you would probably just set y to 0 all the time
You can't.
It seems Like your main Image file is having bigger size the 320x180. You have select area of 320 x 180 which is smaller then your actual Image.
So Here what you can do is.
Calculate Area and set it up in your code. For this, calculate New Height / Width On the bases of Height and Width Of Image; taking other parameter as master. (e.g for your image in question, Master parameter is Width and you can find a new Height which is based on aspect ratio and master parameter.)
Setup area coordinates.
I think this will solve your issue.

Getting data through a PHP file using AJAX+JQuery

I'm working on a gallery that pulls up a full image inside a tooltip when hovering over thumbnails. The problem is, these full images commonly go outside the viewfinder. To remedy this, I'm moving the tooltip if the image will go outside the window boundaries, which requires immediately knowing the images dimensions (to avoid the tooltip jumping around).
However, the images take a bit to load (.gifs) so I can't wait on DOM in order to get the dimensions. So, I'm calling a PHP script to return the the image dimensions before they load.
The problem I'm having is that there's no response from my $.get call. I know the PHP script is working fine, but I'm not getting any data back from it through jquery. Any help would be greatly appreciated. Thanks!!
hover.js:
this.imagePreview = function(){
$("a.preview").hover(function(e){
var viewHeight = $(window).height() + $(window).scrollTop();
var viewWidth = $(window).width();
var xOffset=e.pageX+40;
var yOffset=e.pageY+40;
var url = 'http://mysite.com/i/' + this.href.slice(20);
var w = 0;
var h = 0;
$("body").append("<div id='preview'><img src=" + url +" id='img'/></div>");
$.get("getDimensions.php/?img=" + url, function(data){
w = data.w;
h = data.h;
$("body").append("INFO ABOUT IMAGE DIMENSIONS TRIGGERED: " + w + h);
});
$("#preview")
.css("top",yOffset + "px")
.css("left",xOffset + "px")
.fadeIn("fast");
$('#img').load(function() {
if((e.pageX+img.width)>viewWidth) { xOffset=e.pageX-img.width-70; }
if((e.pageY+img.height)>viewHeight) { yOffset=e.pageY-img.height-70; }
$("#preview")
.css("top",yOffset + "px")
.css("left",xOffset + "px")
.fadeIn("fast");
});
},
function(){
$("#preview").remove();
});
};
// starting the script on page load
$(document).ready(function(){
imagePreview();
});
getDimensions.php:
<?php
list($width, $height, $type, $attr) = getimagesize($img);
echo json_encode(array("w"=>$width,"h"=>$height));
?>
$("body").append("<div id='preview'><img src=" + url +" id='img'/></div>");
when u append the img which have src prop,that will not fire load event any more.That's the problem is.
Have you tried..
var rand = Math.floor(Math.random()*11);
$.get("getDimensions.php/?img=" + url + "&r=" + rand, function(data){
w = data.w;
h = data.h;
$("body").append("INFO ABOUT IMAGE DIMENSIONS TRIGGERED: " + w + h);
},"json");
( Also, I would strongly recommend .ajax over .get)
Can you view what you are getting back from getDimensions.php (in firebug)?
My guess is that jQuery has no way of knowing that the data returned from getDimensions.php is JSON (as opposed to plain old text), and it isn’t trying to parse it.
What's the value of data (if you print it out to the console)?
If this is the problem, you can solve it by adding this line to the PHP script, before echo:
header('Content-Type: application/json');

Categories