How to save a image coded in Data-URI? - image

I'm trying to find a trick to save a picture coded in Data-URI like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA1MAAAE7CAYAAAA4gNuCAAAgAElEQ…
i/fPjJwSa8k8blB7TPIbffod14w9E/Baq03hUCXPf2/wK6K8SbNo44VwAAAABJRU5ErkJggg==
Another question: Where the picture is saved in the first time in the server? Browser?

JS: save image to user's disk using javascript,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
window.onload = function () {
var img = document.getElementById('embedImage');
var button = document.getElementById('saveImage');
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA'+
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO'+
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
img.onload = function () {
button.removeAttribute('disabled');
};
button.onclick = function () {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
};
};
</script>
</head>
<body>
<img id="embedImage" alt="Red dot"/>
<input id="saveImage" type="button" value="save image" disabled="disabled"/>
</body>
</html>
PHP: http://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
EDIT JS solution 2 (fiddle: http://jsfiddle.net/KAdN8/):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
var img = document.getElementById('embedImage');
if( document.createEvent ) {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'click', true, false );
img.dispatchEvent(evObj);
} else if( document.createEventObject ) {
img.fireEvent('on'+evt);
}
</script>
</head>
<body>
Download
</body>
</html>

Related

d3.js v5 stratify returning missing: 0

I have created a very simple test case to use the D3.JS v5 stratify method. Everything looks to be in order based on similar code but mine fails and I am not sure why. Can anyone help?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
let csvdata =
`pk,firstname,lastname,email,title,city,statecode,zip,phone,latitude,longitude,fk_staff
1,Thomas,Bellmer,thomas.bellmer#gmail.com,President,Overland Park,KS,66221,9132216533,38.86182,-94.71264,
2,Xnx,Zgulx,xnx.zgulx#gmail.com,Vice President,Royal Palm Beach,FL,33421,5615120044,26.6802,-80.204984,1
3,Kjc,Duxuk,kjc.duxuk#gmail.com,Vice President,Newtown,IN,47969,7656204292,40.205844,-87.148287,1`
;
data = d3.csvParse(csvdata);
data.forEach(function(d) {
d.pk = +d.pk;
d.fk_staff = +d.fk_staff;
});
console.log(data);
let root = d3.stratify()
.id(function(d) { return d.pk; })
.parentId(function(d) { return d.fk_staff; })
(data);
console.log(root);
</script>
</body>
</html>
The issue is happening here:
data.forEach(function(d) {
d.pk = +d.pk;
d.fk_staff = +d.fk_staff;
});
Some of the data has an empty string as d.fk_staff. When the empty string is coerced to a number it becomes 0, and there is no data with d.pk equals to 0, hence the error.
A simple fix is to not coerce the empty string:
data.forEach(function(d) {
d.pk = +d.pk;
d.fk_staff = d.fk_staff === '' ? '' : +d.fk_staff;
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
let csvdata =
`pk,firstname,lastname,email,title,city,statecode,zip,phone,latitude,longitude,fk_staff
1,Thomas,Bellmer,thomas.bellmer#gmail.com,President,Overland Park,KS,66221,9132216533,38.86182,-94.71264,
2,Xnx,Zgulx,xnx.zgulx#gmail.com,Vice President,Royal Palm Beach,FL,33421,5615120044,26.6802,-80.204984,1
3,Kjc,Duxuk,kjc.duxuk#gmail.com,Vice President,Newtown,IN,47969,7656204292,40.205844,-87.148287,1`
;
data = d3.csvParse(csvdata);
data.forEach(function(d) {
d.pk = +d.pk;
d.fk_staff = d.fk_staff === '' ? '' : +d.fk_staff;
});
console.log(data);
let root = d3.stratify()
.id(function(d) { return d.pk; })
.parentId(function(d) { return d.fk_staff; })
(data);
console.log(root);
</script>
</body>
</html>

Undefined property: Main::$upload , Codeigniter

I am trying to upload single image using codeigniter. But getting error
"Undefined property: Main::$upload
Filename: controllers/Main.php
Line Number: 14"
This is my controller file "controller/Main.php"
<?php
class Main extends CI_Controller
{
public function index(){
$this->load->view('main_view', array('error' => ''));
}
public function upload(){
$config['upload_path'] = "./images/";
$config['allowed_types'] = 'jpg|png|gif';
$this->load->initialize('upload', $config);
if(!$this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('main_view', $error);
}
else {
$file_data = $this->upload->data();
$data['img'] = base_url().'/images/'.$file_data['file_name'];
$this->load->view('success_msg', $data);
}
}
}
?>
and this is my view file "views/main_view.php"
<!DOCTYPE html>
<html>
<head>
<title>Image</title>
</head>
<body>
<?php echo $error; ?>
<?php echo form_open_multipart('main/upload');?>
<input type="file" name="userfile" />
<input type="submit" name="Submit" value="upload image"/>
</form>
</body>
</html>
when image upload is successful I'm trying to show the image by this "view/success_msg.php"
<!DOCTYPE html>
<html>
<head>
<title>Image</title>
</head>
<body>
<h1>File has been uploaded.</h1>
<img src="<?php $img?>" width="300" height="300">
</body>
</html>
my image folder name is "images" and it is in the root directory. Please help my why I am having this error ?
Maybe the upload library isn't loaded. Change the first few lines ofpublic function upload() to the following
public function upload(){
$config['upload_path'] = "./images/";
$config['allowed_types'] = 'jpg|png|gif';
$this->load->library('upload', $config);
By sending $config to load->library you do not need to use initialize().
Controller
public function upload(){
$cc = $_FILES['userfile']['name'];
$extension = pathinfo($cc, PATHINFO_EXTENSION);
$newfile = preg_replace('/[^A-Za-z0-9]/', "", $_FILES["userfile"]['name']);
$config['file_name'] = time() . $newfile;
$ss = ".";
$picture1 = time() . $newfile . $ss . $extension;
$config['upload_path'] = "./images/";
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
echo $this->upload->display_errors();
} else {
$this->load->view('success_msg', $picture1 );
}
}
View page
<!DOCTYPE html>
<html>
<head>
<title>Image</title>
</head>
<body>
<?php echo $error; ?>
<?php echo form_open_multipart('main/upload');?>
<input type="file" name="userfile" />
<input type="submit" name="Submit" value="upload image"/>
</form>
</body>
</html>
view/success_msg.php
<!DOCTYPE html>
<html>
<head>
<title>Image</title>
</head>
<body>
<h1>File has been uploaded.</h1>
<img src="<?php $picture1 ?>" width="300" height="300">
</body>
</html>

i need to hide a dynamically created div using dynamically created button using jquery constructor function

<!DOCTYPE html>
<html>
<head>
<script src='jquery-1.11.2.js' type="text/javascript"></script>
<div id='divn'></div>
<script>
function createDomControls(id,appendToId)
{ this.id=id;
this.appendToId=appendToId;
this.divTag=function(divId,className,style,appendToId)
{
//var divId = "div" + Math.floor((Math.random() * 100000) + 1);
$('<div/>', {
id: divId,
style: style,
class:className
}).appendTo('#' + appendToId);
}
this.buttonTag=function(type,id,value,appendToId)
{
$('<input/>',{
type:type,
id:id,
value:value,
onclick:onclick function(){
$('#div1').hide();
}
});
}
}
var domControls=new createDomControls('divm','divn');
var div=domControls.divTag('div1','cls','background:pink;width:500px;height:670px;padding:12px;margin:0px;','divn');
var btn=domControls.buttonTag('button','btn1','+','div1');
</script>
</head>

Change Image width Ajax, browser memory leaks

This is my html test page:
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<style type="text/css">
#imager img{
width: 1050px;
height:650px;
}
</style>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var index = 0;
var max = 1;
//! get next image
function getImage(){
if (index >= max ) index = 0;
var objTest = {
"index" : index++
};
$.ajax({
type: 'POST',
url: "prova.php",
data: objTest,
success: function(response){
max = response.max;
imageToLoad = response.imageToLoad;
//! Clean div
$("#imager").html("");
//! Display new image
$("#imager").append("<img src='"+imageToLoad+"'></img>");
},
dataType: "json"
});
}
</script>
</head>
<body>
<button onclick="getImage()">get img</button>
<div id="imager"></div>
</body>
And this is my prova.php test page:
$max = 0;
$imgToLoad = null;
// Open image dir
if ($handle = opendir('img')) {
while (false !== ($entry = readdir($handle))) {
if($entry == '.' || $entry == '..' ) continue;
if($_POST['index'] == $max)
// Save next image to show
$imgToLoad =$entry;
// Image counter
$max++;
}
closedir($handle);
}
$array = array(
"max" => $max,
"imageToLoad" => "http://192.168.1.96/prove/cache/img/".$imgToLoad
);
// Return next image and max number of image the we can show
echo json_encode($array);
The problem is that every time that i call "getImage()" the memory browser incrase ( IE and Firefox tested).
My 'img' folder contains a lot of very huge images, about 4600x3000px (400kb), and after a little time the memory brower is about 1 gb and so on.
Thanks for help

No active access token with ajax based app

I am developing an app with 2 files:
index.php (application container)
process.php (called in ajax)
index.php
<?php
include 'config.php';
include 'lib/functions.php';
require_once 'lib/sdk/facebook.php';
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => SECRET
));
$userID = $facebook->getUser();
if (!$userID)
{
$scope = 'read_stream, publish_stream, user_likes, user_photos, user_status, friends_hometown, friends_location, friends_likes, photo_upload';
$params = array(
'scope' => $scope,
'redirect_uri' => "https://apps.facebook.com/".APP_NAME."/"
);
$loginUrl = $facebook->getLoginUrl($params);
}
else
{
$access_token = $facebook->getAccessToken();
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Facebook App</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link href="/css/style.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="/js/jquery.js"></script>
</head>
<body style="margin:0 !important; padding: 0 !important;">
{ SOME HTML }
<script type="text/javascript">
function loadData()
{
$.ajax({
url: "process.php",
type: 'POST',
cache: false,
data: {
id_sessione: function(){return $("#id_sessione").val();}
},
dataType: "json",
success: function(data) {
if (data.status == "FAILURE")
alert('failure');
else
console.log(data);
}
});
}
/********* INIT ********/
$(document).ready(function(){
if ($("#userID").val() != "0")
loadData();
else
top.location = '<?php echo $loginUrl; ?>';
});
</script>
<input id="id_sessione" type="hidden" value="<?php echo session_id(); ?>" />
<input id="userID" type="hidden" value="<?php echo $userID; ?>" />
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo APP_ID; ?>',
frictionlessRequests: true
});
FB.Canvas.setAutoResize(7);
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/it_IT/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
and process.php
<?php
session_id($_POST['id_sessione']);
session_start();
include 'config.php';
include 'lib/functions.php';
require_once 'lib/sdk/facebook.php';
set_time_limit(120);
$memory_limit = ini_set('memory_limit', '512M');
try
{
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => SECRET
));
$userID = $facebook->getUser();
$user_profile = $facebook->api('/me');
{ SOME FQL QUERIES AND DATA PROCESSING }
echo json_encode(array(
'status' => 'SUCCESS',
.... other info
));
} catch (Exception $e) {
$handle = fopen(ROOT_PATH.'/log/'.$userID.'_'.uniqid().'.txt', 'a+') or die('Cannot open file');
fwrite($handle, $e->getMessage()."\n");
fwrite($handle, $e->getTraceAsString()."\n");
fclose($handle);
echo json_encode(array(
'status' => 'FAILURE'
));
}
In 95% of cases application works fine but sometimes $facebook->api('/me'); trows the exception "An active access token must be used to query information about the current user." and the $userID is equal to 0.
In order to have the same session id in all files I have to start manually session with the session_id passed by index.php in POST. This is because some browser (IE, safari) don't pass cookies of third party pages in iframe. (http://stackoverflow.com/questions/9930671/safari-3rd-party-cookie-iframe-trick-no-longer-working)
Any suggestions?
Thank you
check whether the session value is passing properly or not?

Resources