Image from Flash BitmapData to PHP to webpage - php

I'm trying to display an image exported from a flash BitmapData in a basic webpage.
The export from flash works perfectly :
import flash.display.BitmapData;
var vBitmap = new BitmapData(300, 400, true, 0x000000);
vBitmap.draw(themovieclip_mc);
btn1.onRelease = function() {
var vLV = new LoadVars();
vLV.tableData = new Array();
for (i=0; i<300; i++) {
for (j=0; j<400; j++) {
vLV.tableData.push(vBitmap.getPixel(j, i));
}
}
vLV.send("webpage.php", "_self", "POST");
};
Then I get the image in the webpage.php file
<?php
$lv = $_POST['tableData'];
$temp = explode(",",$lv);
settype($temp[1],'integer');
$img = imagecreatetruecolor(300,400);
$k = 0;
for($i=0; $i<300; $i++){
for($j=0; $j<400; $j++){
imagesetpixel($img,$j,$i,$temp[$k]);
$k++;
}
}
$temporary_file_name = tempnam("/tmp");
imagejpeg($img,"$temporary_file_name",100);
?>
<html>
<img src="/tmp/<?php echo $temporary_file_name; ?>" />
<h1>Lorem ipsum</h1>
<p>lorem ipsum dolor sit amet</p>
</html>
the above code does NOT work, I can't find a way to display the image embedded in the webpage. Any help woud be really appreciated.

I am assuming that the insertion of the image data into the web page is your only problem. (without data, it's impossible to tell how well the image generation process itself works.)
I can't find a way to display the image embedded in the webpage
There isn't any good way to do this. You need to get the image from a separate image resource, there's no way around it (except data: URIs but those are broken).
You could write the avatar file into a temporary file:
$temporary_file_name = tempnam("/path/to/somedir");
imagejpeg($img,"$temporary_file_name",100);
then in the HTML, output:
<img src='/somedir/<?php echo $temporary_file_name; ?>' />
you would have to add some mechanism to remove the temporary file later.

So, I finally found my way through this.
That might not be the best way to do it, but at least it works.
//AS3
import com.adobe.images.JPGEncoder;
function createJpg(aMovieClip, aQuality){
var vSource = new BitmapData(200, 304, true, 0 );
vSource.draw(aMovieClip, new Matrix(1,0,0,1,100,152)); // decale de width/2 et height/2
var vEncoder = new JPGEncoder(aQuality);
var vByteArray = vEncoder.encode(vSource);
return vByteArray;
};
// export image to server
function exportJpg(aMovieClip){
var vByteArray = createJpg(aMovieClip, 80);
var vRequest:URLRequest = new URLRequest('URL_TO_THE_PHP_FILE');
var vLoader: URLLoader = new URLLoader();
vRequest.contentType = 'application/octet-stream';
vRequest.method = URLRequestMethod.POST;
vRequest.data = vByteArray;
navigateToURL(vRequest, "_self");
};
// save image on users computer
function saveJpg(aMovieClip, aString){
var vByteArray = createJpg(aMovieClip, 80);
var vFR = new FileReference();
vFR.save(vByteArray, aString);
};
Then the PHP/HTML file
<?php
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$img = $GLOBALS["HTTP_RAW_POST_DATA"];
$prefix = "foo";
$path = "/full/server/path/to/directory/with/777/permissions";
// give a unique name to the file
$name = $prefix.md5(time().rand());
$temporary_file_name = $path.'/'.$name.'.jpg';
$fp = fopen($temporary_file_name, 'wb');
fwrite($fp, $img);
fclose($fp);
// find the name of the image without the full server path
$array = explode("/", $temporary_file_name);
$length = count($array);
$filename = $array[$length - 1];
//give a path to the image file
$imagepath = "http://www.domain.com/directory/".$filename;
}else{
// error : the POST data was not found
}
?>
<html>
<head>
</head>
<body>
<h1>Lorem ipsum</h1>
<p><img src="<?php echo $imagepath; ?>"</p>
</body>
</html>

Related

How to call an image alt by an onclick event using php?

I want to open a new page and transfer data from an array. Using the name of the image seemed like the easiest way so that's what i want to do.
on the page i want to call it
function meghiv($img)
{
$be=$img.alt;
echo $be;
session_start();
$_SESSION['kod'] = $be;
}
for($j=0;$j<4;$j++)
{
echo ' <img src="'.$nevek[$i].'.png" class="card-img-top " alt="'.$i.'" onclick="meghiv(this)"> ';
$i++;
}
on the new page
<?php
session_start();
echo $_SESSION['kod'];
?>
I don't know if it answers your question but try using javascript to load the image name into your php file
let images = document.querySelectorAll('.card-img-top'); // returns NodeList
let img_list = [...images]; // converts NodeList to Array
img_list.forEach(div => {
div.addEventListener("click", function(e){
e.preventDefault()
let alt = div.getAttribute("alt")
window.open(`https://link.here/?alt=${alt}`, "_blank");
})
});
Then in your php file
$image_name = $_GET['alt'];

Issue converting obj (3d) to png [duplicate]

How would I convert a render to a .png image?
I've been looking around for awhile but nothing has worked.
Here is a function I use and a fiddle that shows it working.
function takeScreenshot() {
// For screenshots to work with WebGL renderer, preserveDrawingBuffer should be set to true.
// open in new window like this
var w = window.open('', '');
w.document.title = "Screenshot";
//w.document.body.style.backgroundColor = "red";
var img = new Image();
img.src = renderer.domElement.toDataURL();
w.document.body.appendChild(img);
// download file like this.
//var a = document.createElement('a');
//a.href = renderer.domElement.toDataURL().replace("image/png", "image/octet-stream");
//a.download = 'canvas.png'
//a.click();
}

PHP doesn't seem to be processing script to post to MySQL

I'm using html5 canvas to capture a signature and store it in MySQL. I've got everything in the script working except for the part that saves the signature and sends it to MySQL.
My knowledge of AJAX is none so I'm working off what I read in books, see on tutorials and get help on from here.
So in Firefox console when I click on save signature I can see the script displays the post.php file it's supposed to go to and displays a 200 ok notification but nothing happens, it doesn't post in MySQL (which doesn't surprise me as I'm sure my code is incorrect) and I don't see any errors.
What I want to accomplish is to upload the signature image to a folder on the server and save the path to the image in MySQL. Being unfamiliar with JavaScript, Jquery and Ajax I'm confused with how to get this to function.
Here is the jquery:
$(document).ready(function () {
/** Set Canvas Size **/
var canvasWidth = 400;
var canvasHeight = 75;
/** IE SUPPORT **/
var canvasDiv = document.getElementById('signaturePad');
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if (typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
var context = canvas.getContext("2d");
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
/** Redraw the Canvas **/
function redraw() {
canvas.width = canvas.width; // Clears the canvas
context.strokeStyle = "#000000";
context.lineJoin = "miter";
context.lineWidth = 2;
for (var i = 0; i < clickX.length; i++) {
context.beginPath();
if (clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
context.moveTo(clickX[i] - 1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
/** Save Canvas **/
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$("#imgData").html('Thank you! Your signature was saved');
var ajax = XMLHttpRequest();
ajax.open("POST", 'post.php');
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(sigData);
// $('#debug').html(sigData);
});
/** Clear Canvas **/
$('#clearSig').click(
function clearSig() {
clickX = new Array();
clickY = new Array();
clickDrag = new Array();
context.clearRect(0, 0, canvas.width, canvas.height);
});
/**Draw when moving over Canvas **/
$('#signaturePad').mousemove(function (e) {
if (paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
/**Stop Drawing on Mouseup **/
$('#signaturePad').mouseup(function (e) {
paint = false;
});
/** Starting a Click **/
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
$('#signaturePad').mousedown(function (e) {
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
});
and here is the PHP: Also I didn't write the php code below it's part of the entire signature pad so I'm sure it's not correct.
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$session_id = $_SERVER['REMOTE_ADDR'];
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
$imageName = "sign_" . rand(5,1000) . rand(1, 10) . rand(10000, 150000) . rand(1500, 100000000) . ".png";
//Set the absolute path to your folder (i.e. /usr/home/your-domain/your-folder/
$filepath = "xampp/htdocs/alpha/site7/images/" . $imageName;
$fp = fopen("$filepath", 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
//Connect to a mySQL database and store the user's information so you can link to it later
$link = mysql_connect('localhost','root', 'password') OR DIE(mysql_error);
mysql_select_db("customer", $link);
mysql_query("INSERT INTO 'signature' ('session', 'image_location') VALUES ('$session_id', '$imageName')") OR DIE(mysql_error());
mysql_close($link);
}
?>
And the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Signature Pad</title>
<!-- The Signature Pad -->
<script type ="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="signature-pad.js"></script>
</head>
<body>
<center>
<fieldset style="width: 435px">
<br/>
<br/>
<div id="signaturePad" style="border: 1px solid #ccc; height: 55px; width: 400px;"></div>
<br/>
<button id="clearSig" type="button">Clear Signature</button>
<button id="saveSig" type="button">Save Signature</button>
<div id="imgData"></div>
<div
<br/>
<br/>
</fieldset>
</center>
<div id="debug"></div>
</body>
</html>
After some head beating over this I've finally been able to discover some errors.
After signing the signature pad and pressing the save signature button I get these errors in Firebug
Warning: fopen(xampp/htdocs/alpha/site6/images/sign_42281643871777767.png): failed to open stream: No such file or directory in C:\xampp\htdocs\alpha\site6\post.php on line 20
Warning: fwrite() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\alpha\site6\post.php on line 21
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\alpha\site6\post.php on line 22
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''signatures' ('session', 'image_location') VALUES ('127.0.0.1', 'sign_42281643871' at line 1
Since I don't have any knowledge of Jquery or Ajax and how they are creating the image and attempting to post it to a folder I'm pretty much stuck at this point!
seems I'm answering my own problems, I've figured out what the fopen errors were, I wasn't using an absolute path so adding a / before the start of the path cleared up everything except for the last error of this:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''signature' ('session', 'image_location') VALUES ('127.0.0.1', 'sign_11814198867' at line 1

html2canvas output selected div PHP

this code almost works
this will output the entire page into a jpg
question: how can i grab only the content inside '#myDiv' and output that as a jpg file?
JS:
$('.myButton').click(function(){
$('#myDiv').html2canvas();//<< has no effect
var queue = html2canvas.Parse();
var canvas = html2canvas.Renderer(queue,{elements:{length:0}});
var img = canvas.toDataURL();
img.replace(/^data:image\/(png|jpg);base64,/, "");
$.post( "postIO.php", {img:img}, function(data) {
//$('#recieve').append(data);
});
return false;
});
postIO.php:
$canvasImg = $_POST['img'];
//$canvasImg = str_replace('data:image/png;base64,', '', $canvasImg);
$data = base64_decode($canvasImg);
$File = "z.jpg";
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
fclose($Handle);
reference from here
I have download and try html2canvas, then I find out the jquery plugin does not complete (it's does nothing than capture the image and create canvas, no use) so I write capture code myself.
var el = $('div').get(0);
function saveData(dturl){
//Upload here
console.debug(dturl);
}
html2canvas.Preload(el, {
complete: function(image){
var queue = html2canvas.Parse(el, image, {elements: el}),
$canvas = $(html2canvas.Renderer(queue, {elements: el}));
saveData($canvas[0].toDataURL());
}
});
Hope it help you
so to use with your program you have to write
function saveData(dturl){
dturl.replace(/^data:image\/(png|jpg);base64,/, "");
$.post( "postIO.php", {img:dturl}, function(data) {
//$('#recieve').append(data);
});
}
$('.myButton').click(function(){
var el = $('#myDiv').get(0);
html2canvas.Preload(el, {
complete: function(image){
var queue = html2canvas.Parse(el, image, {elements: el}),
$canvas = $(html2canvas.Renderer(queue, {elements: el}));
saveData($canvas[0].toDataURL());
}
});
});
after var canvasImg = canvasRecord.toDataURL("image/jpg");, you may need to replace it using var data = canvasImg.replace(/^data:image\/(png|jpg);base64,/, "");
and is that $canvasImg = $_POST['canvasImg']; instead of $_POST['img']?

Pull img src from this html grabbed with javascript

I am extracting an image from a part of the document using:
var theImg = document.getElementById('imageDiv').innerHTML;
This returns something like
theImg = <img src="http://website.com/image.jpg?&image-presets&" alt="foo" style="z-index: 1" />
How could I grab just the src of the image, without the parameter. So that
theImg = http://website.com/image.jpg
I am open to using a regular expression, php, or vanilla javascript.
Untested, but I believe this should do the job. It first retrieves the image src and then strips off everything starting with the ?.
var imgDiv = document.getElementById('imageDiv');
var imgs = imgDiv.getElementsByTagName("img");
for (var i = 0; i<imgs.length; i++) {
var theImg = imgs[i].getAttribute('src').substr(0, theImg.indexOf('?'));
console.log(theImg);
// Do whatever you need to with theImg. Add to an array or whatever...
}
Since there appear to be no correct and complete answers so far with a working demonstration, I'll attempt one:
var imgs = document.getElementById('imageDiv').getElementsByTagName('img');
var theImgSrc = imgs[0].src;
var loc = theImgSrc.indexOf("?");
if (loc != -1) {
theImgSrc = theImgSrc.substr(0, loc);
}
You can see it in action here: http://jsfiddle.net/jfriend00/NSczd/
Just call .getAttribute('src') on the image element itself, and assign that string to theImg.
More fully, the following:
var theImg = document.getElementById('your_image').getAttribute('src');
Handles both parts of the question:
var imgDiv = document.getElementById('imageDiv');
var imgs = imgDiv.getElementsByTagName("img");
var url = "";
if (imgs.length > 0) {
var img = imgs[0];
var questionIndex = img.src.indexOf("?");
if (questionIndex > -1) {
url = img.src.substring(0, questionIndex);
} else {
url = img.src;
}
}
alert(url);
http://jsfiddle.net/cvhwZ/2/
Sorry, yeah, this is better.
var theImgSRC = document.getElementById('imageDiv').querySelector('img').getAttribute('src');
document.getElementById('imageDiv').querySelector("img").getAttribute('src').theImg.substr(0, theImg.indexOf('?'));

Categories