Javascript Form validation for field image uplaod? - php

I make a form validation with javascript for field image upload but i stuck on point of how to validate image size(width and height) through javascipt for only 600 width and 300 height image is post by form .
So guys if you have any solution are demo code share with mi .
Thanks in advance !

You can use following function in javascript side to check whether image has desired resolution or not.
If it has correct resolution than proceed with form submission otherwise show error message.
var _URL = window.URL || window.webkitURL;
$("#file").change(function(e) {
var file, img;
if ((file = this.files[0])) {
img = new Image(); // create a Image object which contain height & width property of image
img.onload = function() {
alert(this.width + " " + this.height);
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});

Related

Save images in XAMPP server from Cordova with PHP

My requirement is to save the images taken from Camera of Cordova plugin and save the image in a server . I have used below code and achieved getting the image , but how do i save in a server using PHP
// Code to capture photo from camera and show gps co ordinates
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64-encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
// button to capture photo
<button onclick="capturePhoto();">Capture Photo</button> <br>
// button to capture editable photo
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
//button to select images from library
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
PHP Code (upload.php):
<?php
print_r($_FILES);
move_uploaded_file($_FILES["file"]["tmp_name"], "192.168.3.153/uploads/".$_FILES["file"]["name"]);
?>
The only way to do this is to get the image as a Base64 encoded string, send that back to the server and then save it into the DB, either in encoded form, or decode it and then save it as a file on the server or a blob in a database.
I don't know the exact implementation procedure as I'm not a Cordova dev, I just sit next to one at work who was tearing his hair out over something similar recently.
In cordova we have plugin file transfer which is used to download / upload files from server. You have to use this plugin to upload image taken from camera.
Check following link that details how to upload file to server
Following is a Javascript function that picks a file stored in mobile device and send it to server
function uploadfiletoserver(filename){ // where filename is the file store in device
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
//The folder is created if doesn't exist
fileSys.root.getDirectory( 'APP STORAGE FOLDER', {create:true, exclusive: false},
function(directory) {
//find the file
directory.getFile(filename, {create: false, exclusive: false},
function(file){
var imageURI = file.toInternalURL();
var options = new FileUploadOptions();
options.fileKey = "uploadfile"; //this is the value use to refer the file uploaded to server e.g. $_FILES['uploadfile']
options.fileName = file.name;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI('http://www.yourdomain.com/upload.php'), function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}, function (error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}, options);
console.log("upload file: "+imageURI);
},
function(error){
console.log("Error "+error);
}
);
},
resOnError);
},
resOnError);
}
In server PHP file,
<?php
$tmpName = $_FILES['uploadfile']['tmp_name'];
$fileName = $_FILES['uploadfile']['name'];
$fileDestPath = 'YOUR_UPLOAD_FOLDER_IN_SERVER'.$fileName;
if($tmpName != 'none') {
move_uploaded_file($tmpName, $fileDestPath);
}
?>

get jquery image width and add class

I'm having trouble getting the dimensions of a series of images that are loading via PHP.
<?
$Ldir="imgs/liveGallery/"; // Directory where files are stored
if ($Lhandle = opendir($Ldir)) {
while (false !== ($Lfile = readdir($Lhandle))) {
if ($Lfile != "." && $Lfile != "..") $Lthefiles[] = $Lfile;
}
closedir($Lhandle);
}
sort($Lthefiles);
for ($Li=0;$Li<count($Lthefiles);$Li++) { ?>
<a href="<?php echo $Ldir.$Lthefiles[$Li]; ?>" class="ilightbox">
<div class="adj">
<img src="<?php echo $Ldir.$Lthefiles[$Li]; ?>" class="percent">
</div>
</a>
<?php }
?>
In the above code PHP is doing its job loading all the images from a nearby directory. The .adj class is formatting the <div> into a square and floating them all to the left so they tile the screen. It's also hiding the overflow so that no matter the dimensions all you see is a square.
My issue comes when trying to read the widths and heights of the images that are being loaded into that <div>. I want to have the image fit at a width or height of 100% depending on which is proportional to fill the square. Here's the jquery code I thought should work.
$(window).load(function() {
$(".adj").each(function() {
var $this = $(this);
var imageWidth = $this.children("img").attr("width");
var imageHeight = $this.children("img").attr("height");
if (imageWidth < imageHeight){
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
});
});
I don't seem to be capturing an image width or height at all, with what I wrote above.
I'm using fullpage.js and ilightbox.js which may be messing with my code, but I doubt it. I've also tried putting a modified version of this code inside the PHP for loop (without the jquery each function) and that doesn't work either. HELP!
Here's a link for you.
You can try somethig like
$(window).load(function() {
$(".adj").each(function () {
var $this = $(this);
var img = new Image();
//Set Image source
img.src = $this.children("img").attr("src");
//Wait for image to be loaded.
//Event will fire when image is loaded
img.onload = function () {
//Get Height and width
var imageWidth = img.width;
var imageHeight = img.height;
if (imageWidth < imageHeight) {
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
};
});
});
Note: I am not sure, this is a best practice
You have set the width and height in the css styling and not inline as attributes,
So attributes width and height are empty
$this.children("img").attr("width"); // .attr would not work
Should be
$this.children("img").css("width"); // .css is the method
And
$(window).load(function() {
$(".adj").each(function() {
var $this = $(this);
// when your referring same img multiple times, grab it in a variable
var image = $this.children("img");
var imgWidth = image.width(); // or image.css("width")
var imageHeight = image.height(); // or image.css("height")
if (imageWidth < imageHeight){
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
});
});
note .css() gives in the px'.
Example 100px even though you set the values in pt or em etc. After seeing your code since your comparing the values I would suggest .width() and .height() as they return integer values and easy to compare
jQuery documentation
Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "width" ) rather than .width()

Blur image with pixastic and set it as background with jquery

i have a problem that is bothering me form 2 days.
I'm developing a little music sharing site and i have a problem making the design for the player.
I want to apply a blurred image background to a div with CSS and with the blur begin applied on the image via JS all with pixastic js library. The problem is that pixastic gives me a HTMLImageElement witch i can't apply to a css with $('.footer').css('background', "url(" + img.toDataURL("image/png")+ ")" }); since toDataURL works only with canvas elements.
How can i do that?
My code so far is:
var img = new Image();
img.src = '<?php echo $hd ?>';
img.onload = function() {
Pixastic.process(img, "blurfast", {amount:1});
}
$('.footer').css('background', "url(" + img.toDataURL("image/png")+ ")" });
The $hd is a http url that points to an album artwork using lastfm API
I'm not sure about first argument of css method and why you dont use img.src as url of image? Try something like this:
$('.footer').css('background-image', 'url(' + img.src + ')');
Ok I found probably answer on documentation:
var options = {};
Pixastic.process(image, "action", options);
options.resultCanvas; // <- holds new canvas
So in your case it would be:
var img = new Image(),
options = {};
options.amount = 1
img.src = '<?php echo $hd ?>';
img.onload = function() {
Pixastic.process(img, "blurfast", options);
$('.footer').css('background', "url(" + options.resultCanvas.toDataURL("image/png")+ ")" });
}

Save Google charts as a image

So after hours of websearching, googling and overflowing i can't find the solution to my problem.
I got a linechart from Google charts. I want to convert it to PNG, save it on the server en insert it into a MySQL database.
Sounds simple, but i cant get it to work. The script from this website isnt working anymore (atleast not here) http://www.battlehorse.net/page/topics/charts/save_google_charts_as_image.html -> Not working.
Second option is the old option:
$imageData = file_get_contents('http://chart.apis.google.com/chart... etc');
I cant use that because its not supported anymore and cant get some decent quality out of it.
Is there anybody here that can give a good tutorial or help for my problem?
EDIT:
I used the code from Battlehorse combined with the code from EriC.
So now i got this working to show the chart as an image in a DIV i want to save this image on the server and update the mysql to use it in the future to use it in PDF files.
When you visit the site, paste this in the console (overwriting the malfunctioning function).
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
}
In JS it was searching for an iframe bla bla to get the svg.
To automatically save the image, you can just let the method being invoked programmatically.
document.body.addEventListener("load", function() {
saveAsImg( document.getElementById("pie_div")); // or your ID
}, false );
For saving images serverside, this post could be helpful save a PNG image server-side
Update
Posting images to PHP (index.js)
function saveToPHP( imgdata ) {
var script = document.createElement("SCRIPT");
script.setAttribute( 'type', 'text/javascript' );
script.setAttribute( 'src', 'save.php?data=' + imgdata );
document.head.appendChild( script );
}
function save() {
var canvas = document.getElementById("canvas"), // Get your canvas
imgdata = canvas.toDataURL();
saveToPHP( imgdata );
}
function drawOnCanvas() {
var canvas = document.getElementById("canvas"), // Get your canvas
ctx = canvas.getContext("2d");
ctx.strokeStyle = "#000000";
ctx.fillStyle = "#FFFF00";
ctx.beginPath();
ctx.arc(100,99,50,0,Math.PI*2,true);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
drawOnCanvas(); // Test
save();
save.php
<?php
// Get the request
$data = $_GET['data'];
// Save to your DB.
?>
You can use the grChartImg library. It's a cross browser solution and supports even old versions of IE (8 and earlier).It has many features such as download image,upload to the server, show the image in a dialog etc.
For more info look at http://www.chartstoimage.eu.
i hope help you.
This is not really an answer but might be one in the future and it is nescesary if you just want the feature back. The following URL shows all the current issues and feature requests for the visualization API.
https://code.google.com/p/google-visualization-api-issues/issues/list?can=2&q=&sort=-stars+id&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Stars
The more stars/votes this feature request gets, the higher the chance they will take a look at it.
I have the same issue - Save Google charts as image on server. None of answers here works for me. Finally I get solution but with some bugs(working only in Chrome browser). As base I used script from here https://gist.github.com/mpetherb/7085315 I made some changes for my project. I use jquery for importing generated graph image to to my server.
This is a graph that I want to convert to image and save google graph example id="ex0"
Script for converting to image and importing to server
<script>
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
}
function toImg(chartContainer, imgContainer) {
var doc = chartContainer.ownerDocument;
var img = doc.createElement('img');
var myimg=img.src = getImgData(chartContainer);
//Here I am using jquery for importing decoded image to hidden.php on my server
$.ajax({
method: "POST",
url: "hidden.php",
data: { name: myimg } });
while (imgContainer.firstChild) {
imgContainer.removeChild(imgContainer.firstChild);
}
imgContainer.appendChild(img);
}
</script>
<button onclick="toImg(document.getElementById('ex0'), document.getElementById('ex0'));"
type="button" <Convert to image and upload on server></button>
// ex0 - div id of this type of google graph. If you using another type of google graph - you should change it
Don't forget include jquery to your code.
and php hidden script for receiving data from jquery method POST and saving it on server
hidden.php file
<?php
if(isset($_POST['name']))
{
$data = $_POST['name'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
file_put_contents('graph_temp.png', base64_decode($data));
I will notice again - works only in Chrome browser. Firefox also create image file on server but without any content (looks like firefox not support base64 encoded data)

Codeigniter: TinyMCE image manager dynamic image paths

I have installed TinyMCE into my codeigniter build, and I have included the image manager.
In the image manager plugin (which is saved in the public/assets folder) there is a php config file which defines the image & file path constants.
define('DIR_IMAGES', 'images/path/here'); etc
The problem I have is I need the path to be dynamic depending on some data in the database, such as template_name, but I dont know how to include the right files into the config file so I can view the dynamic info.
So if the user has a template_name saved then I need the path to be
define('DIR_IMAGES', $template_name.'images/path/here');
I have also defined the template_name in a constant in core/MY_Controller.php so if I could access that variable that would be easier than doing a query to the DB but either way will work.
Can someone give me a hand with this, thanks a lot!
I've just custom tinymce image but not using TinyMCE image manager.
but I use the tutorial from the link below.
How-to implement a custom file browser
<!-- Start tinymce custom -->
<script type="text/javascript">
tinyMCE.init({
<!--
your tiny mce init here
--->
<!-- custom file browser callback -->
file_browser_callback : 'myFileBrowser',
});
function myFileBrowser (field_name, url, type, win) {
// this is your dynamic image path
var cmsURL = "<?php echo base_url() ?>admin/media/select_image"; <== you can set as you wish
if (cmsURL.indexOf("?") < 0) {
//add the type as the only query parameter
cmsURL = cmsURL + "?type=" + type;
}
else {
//add the type as an additional query parameter
// (PHP session ID is now included if there is one at all)
cmsURL = cmsURL + "&type=" + type;
}
tinyMCE.activeEditor.windowManager.open({
file : cmsURL
,width : 600
,height : 600
,resizable : "yes"
,inline : "yes"
,close_previous : "yes"
,popup_css : true // Disable TinyMCE's default popup CSS
}, {
window : win,
input : field_name
});
return false;
}
</script>
Add a "data-" attribute to your tinymce element and echo your desired url from there. Then in tinymce activeEditor, access that data- attribute value.
Textarea
<textarea name="description" class="tinymceDescription" data-uploadLink="<?php echo DIR_IMAGES; ?>" ></textarea>
TinyMce
tinymce.init({
// other settings here
//either use this if you are uploading automatically.
images_upload_url: $(tinymce.activeEditor.targetElm).attr("data-uploadLink"),
//or use this if you want to override tinymce auto upload.
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
var uploadLink = $(tinymce.activeEditor.targetElm).attr("data-uploadLink");
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', uploadLink);
xhr.onload = function () {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure(xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
The point here is to show you how i got a dynamic upload url into tinymce from the currently selected tinymce instance. The way you upload is your choice which i hope you know how to handle. But ether way, i have provide both the automatic and custom examples.

Categories