Flash AS3 PNGEncoder With Base64 and PHP Not Working - php

I am trying to utilize the PNGEncoder with the dynamicfash Base64 to send a Base64 String to PHP and save the PNG File but for some reason that i cannot figure out, the PNG file is never readable. It is there and has a size (contains data) but cannot be opened by anything so is not a valid png file. Here is my code...
var target:MovieClip = new MovieClip();
target.graphics.beginFill(0xff0000,5.0);
target.graphics.drawRect(0,0,100,100);
target.graphics.endFill();
var bdata:BitmapData = new BitmapData(100, 100);
bdata.draw(target);
var stream:ByteArray = PNGEncoder.encode(bdata);
var byteArrayAsString:String = Base64.encodeByteArray(stream);
var request:URLRequest = new URLRequest("pngsave.php");
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.fileName = "testing.png";
variables.image = byteArrayAsString;
request.data = variables;
navigateToURL(request, "_blank");
and the PHP Code...
<?php
header('Content-Type: image/png');
header("Content-Disposition: attachment; filename=".$_POST['fileName']);
echo base64_decode($_POST["image"]);
?>
Any ideas on what I am doing wrong here?

With FlashPlayer 10 (which has >95% adoption rate) you don't need to send the png data to a php page. Just use FileReference.save() instead.

Related

Sending and Recieving PNGencoded to php mysql BLOB

I'm trying to send encoded data for a bitmap image to a server and back to the( or a separate) client. There's probably an easier way to do this with sockets or something, but I'm a very casual and still a pretty new programmer and I had trouble understanding other methods. The encoding and decoding works fine and I can save and open up the encoded png, but somewhere on the php/mysql side the encoded data loses most of it's code.
Actionscript code for sending the encoded data to the php.
var req:URLRequest = new URLRequest("http://host.net//img.php");
req.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader;
var phpvar = new URLVariables();
var shape:MovieClip = new MovieClip();
shape.graphics.beginFill(0xFF0000);
shape.graphics.drawRect(0, 0, 100, 100);
addChild(shape);
var bmp:BitmapData = new BitmapData(500, 350);
bmp.draw(shape);
var byte:ByteArray = new ByteArray();
bmp.encode(new Rectangle(0,0, 100, 100), new flash.display.PNGEncoderOptions(false), byte);
//save on database
phpvar.bytez = byte;
req.data = phpvar;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(req);
trace(req.data.bytez);
The traced output is:
PNG
->
IHDRddÿIDATxÚíÐ1 µçYÁÏ"Ð)®F,Y²dɒ¥#,Y²dÉR
K,Y²d)%K,Y²Ȓ%K,Y dɒ%K,²dɒ%KY²dɒ%K,Y²dɒ¥#,Y²dÉR
K,Y²d)%K,Y²Ȓ%K,Y dɒ%K,²dɒ%KY²dɒ%K,Yß^Çjú··IEND®B`
Actionscript code for recieving data:
var req = new URLRequest("http://host.net//imgsend.php");
var loader = new URLLoader(req);
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onComplete);
loader.load(req);
function onComplete(e:Event) {
var loaderer:Loader = new Loader();
var byte:ByteArray = new ByteArray()
byte = e.target.data;
trace(byte);
}
Traced output is:
PNG
->
For some reason it knows the encoded data is for a PNG, but all there is is a header. I think the problem is in my php/mysql code, but I'm not completely sure here. I'm using a free webhosting service with phpMyAdmin for convenient sake, the Images table is just a BLOB column and the php files are uploaded on the host server.
PHP code for reading and inserting into mysql (img.php)
<?php
mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database) or die(mysql_error());
$pic = $_POST['bytez'];
$sql = "INSERT INTO Images (img) VALUES ('$pic')";
mysql_query($sql);
?>
PHP code for taking the data form the server and sending it to Actionscript (imgsend.php)
<?php
mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database) or die(mysql_error());
$sql = "SELECT * FROM Images";
$records = mysql_query($sql);
while($byte=mysql_fetch_assoc($records)){
echo $byte['img'];
}
?>
I didn't necessarily find an answer to this exact method, but I found an alternate solution, ie writing the file directly into the directory. From what I've read this is much more efficient anyways. The code is basically the same only I added URLcontentType and extended the URL for the URL request address for the file's location.
var req:URLRequest = new URLRequest("http://host.net//img.php?filename=something.png");
req.method = URLRequestMethod.POST;
req.contentType = "application/octet-stream";
var loader:URLLoader = new URLLoader;
var shape:MovieClip = new MovieClip();
shape.graphics.beginFill(0xFF0000);
shape.graphics.drawRect(0, 0, 100, 100);
addChild(shape);
var bmp:BitmapData = new BitmapData(500, 350);
bmp.draw(shape);
var byte:ByteArray = new ByteArray();
bmp.encode(new Rectangle(0,0, 100, 100), new flash.display.PNGEncoderOptions(false), byte);
//save on database
req.data = byte;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(req);
The PHP code is for img.php is:
<?php
$fileName = $_GET['filename'];
$fp = fopen( $fileName, 'wb' );
fwrite( $fp, $GLOBALS['HTTP_RAW_POST_DATA'] );
fclose( $fp );
?>
Loading the file is simple, not going to bother posting that. I'll deal with unique file names on my own, baby steps. Thanks for helping me talk this out some!

PHP's $HTTP_RAW_POST_DATA in ASP

I'm updating a classic asp page with a flash app and I need to reproduce the PHP's $HTTP_RAW_POST_DATA function under vbscript (OR C# .NET since it's on IIS7 also). This is what I have so far but does not work. The browser just tells me that it can not display the image because of errors or corruption. Thanx in advance.
AS3 Code
vid_out = new Video();
vid_out.x = 0;
vid_out.y = 0;
vid_out.width = cam.width;
vid_out.height = cam.height;
vid_out.attachCamera(cam);
addChild(vid_out);
var bitmapData:BitmapData = new BitmapData(640, 480);
bitmapData.draw(vid_out);
var encoder:JPGEncoder = new JPGEncoder();
var byteArray:ByteArray = encoder.encode(bitmapData);
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("/capture.asp?i=blah.jpg");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
navigateToURL(jpgURLRequest, "_blank");
non-working vbscript code
Function RSBinaryToString(xBinary)
Dim Binary
If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary
Dim RS, LBinary
Const adLongVarChar = 201
Set RS = CreateObject("ADODB.Recordset")
LBinary = LenB(Binary)
If LBinary>0 Then
RS.Fields.Append "mBinary", adLongVarChar, LBinary
RS.Open
RS.AddNew
RS("mBinary").AppendChunk Binary
RS.Update
RSBinaryToString = RS("mBinary")
Else
RSBinaryToString = ""
End If
End Function
photoname = trim(request.querystring("i"))
Dim ByteCount, BinRead
ByteCount = Request.TotalBytes
If ByteCount > 0 Then
BinRead = Request.BinaryRead(ByteCount)
Response.ContentType = "image/jpeg"
Response.AddHeader "Content-Disposition", "inline; filename=" & photoname
Response.BinaryWrite(RSBinaryToString(BinRead))
Response.End()
End If
'working vbscript code
I'm just using the actual folder path located on the server. You can user servermappath also.
photoname = trim(request.querystring("i"))
folder = "C:\some_folder\"
tofolder = folder & photoname
Dim BinaryData, ByteCount
ByteCount = Request.TotalBytes
BinaryData = Request.BinaryRead(ByteCount)
Set objADO = Server.CreateObject("ADODB.Stream")
objADO.Type = 1
objADO.Open
objADO.Write BinaryData
objADO.SaveToFile tofolder, 2
Set objADO = Nothing
See Request Object reference
Specifically, you will be interested in Request.TotalBytes property to get request body size and Request.BinaryRead method to read the request body.
Quote from MSDN:
VBScript
<%
Dim vntPostedData, lngCount
lngCount = Request.TotalBytes
vntPostedData = Request.BinaryRead(lngCount)
%>

Upload image by AIR app

Have an issue with Air application and upload the image to server by php.
What I'm doing wrong? On progress everything is alright, is showing progress and response, but php can't find an image.
var request:URLRequest = new URLRequest("http://xxxxxxxxxx/api.php");
request.method = URLRequestMethod.POST;
request.contentType = "application/octet-stream";
var variables:URLVariables = new URLVariables();
variables.action = "addEntry";
variables.user = "1";
request.data = variables;
var file:FileReference = new FileReference();
var filenameSmall:String = "xxxxx/" + _userName+"/thumbnail.jpg";
if(_fb == true)
{
filenameSmall = "xxxxx/" + user +"/thumbnail.jpg";
}
file = File.desktopDirectory.resolvePath( filenameSmall );
file.addEventListener(ProgressEvent.PROGRESS, uploadProgress);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadDataComplete);
file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, uploadError);
file.addEventListener(HTTPStatusEvent.HTTP_STATUS, uploadError);
file.addEventListener(IOErrorEvent.IO_ERROR, uploadError);
file.upload(request, "image");
The upload of file reference could not send any request or variables to php files. It just upload the file to the path you have given in the url. If you want to save an image using php
you should convert the image to byte array,
Do any one the encoding process(either PNGEncoding or JPEGEncoding),
If you want then do any standard encoding(base64) for security
Then send that string to php
Make your php file to read that data and write it.

setRequestHeader Error When Saving Canvas as Image on Server

I have a highcharts svg which I have converted to a png via canvg and displayed on the webpage. I would like to then send this png to the server to create a link to the image. I was following the answer code on another topic:
Renaming an image created from an HTML5 canvas
My javascript code is the following:
var timeout = window.setTimeout(function() {
canvg(document.getElementById('canvas'), chart.getSVG());
}, 10000);
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("images/png");
document.write('<img src="'+img+'"/>');
saveDataURL(img)
function saveDataURL(canvas) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
window.location.href = request.responseText;
}
};
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.open("POST", "saveDataURL.php", true);
request.send("dataURL=" + canvas.toDataURL());
}
My php called saveDataURL.php is then:
$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL)[1];
$decodedData = base64_decode($encodedData);
file_put_contents("temp/faizan.png", $decodedData);
echo "http://whichchart.com/temp/faizan.png";
In firefox 12 the following error is thrown up at the "request.setRequestHeader" line:
Component returned failure code: 0x804b000f (NS_ERROR_IN_PROGRESS) [nsIXMLHttpRequest.setRequestHeader]
http://whichchart.com/oil.js
Line 102
In chrome the error on the same line is:
Uncaught Error: INVALID_STATE_ERR: DOM Exception 11
saveDataURLoil.js:106
(anonymous function)
The example can be viewed here: whichchart.com. Can you help? Thanks.
Ok, so I found a different solution after much searching. The link is here:
http://permadi.com/blog/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/
Assuming you have a canvas called testCanvas, this javascript and php will work:
var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData );
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// 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;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>

Save image from Flash, send it to PHP and return a URL string to Flash

I use this code to convert an image to a BitmapData and store a JPG in a ByteArray.
import com.adobe.images.JPGEncoder;
var jpgSource:BitmapData = new BitmapData (img_mc.width, img_mc.height);
jpgSource.draw(img_mc);
var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
// here we need some code to send the bytearray but I lack enough knowledge to do it by myself
Now, I want to do the following:
1. send the ByteArray to PHP;
2. PHP must store a physical image_id.jpg on server;
3. then PHP must return the URL of the image to Flash;
Is this possible? How?
The first lines of PHP could be:
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// but I don't know how to save the image on disk and how to return the URL of the //image
}
Thanks!
the as3 part:
import com.adobe.images.JPGEncoder;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequestHeader;
import flash.net.URLRequest;
var jpgSource:BitmapData = new BitmapData(img_mc.width,img_mc.height);
jpgSource.draw(img_mc);
var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
//set the request's header,method and data
var header:URLRequestHeader = new URLRequestHeader("Content-type","application/octet-stream");
var loader:URLLoader = new URLLoader();
//sends jpg bytes to saveJPG.php script
var myRequest:URLRequest = new URLRequest("saveJPG.php");
myRequest.requestHeaders.push(header);
myRequest.method = URLRequestMethod.POST;
myRequest.data = jpgStream;
loader.load(myRequest);
//fire complete event;
loader.addEventListener(Event.COMPLETE,saved);
function saved(e:Event)
{
//trace the image file name
trace(loader.data);
}
the php (saveJPG.php) part:
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
//the image file name
$fileName = 'img.jpg';
// get the binary stream
$im = $GLOBALS["HTTP_RAW_POST_DATA"];
//write it
$fp = fopen($fileName, 'wb');
fwrite($fp, $im);
fclose($fp);
//echo the fileName;
echo $fileName;
} else echo 'result=An error occured.';

Categories