Sending and Recieving PNGencoded to php mysql BLOB - php

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!

Related

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)
%>

Flash AS3 Data from PHP XML not showing in datagrid

My PHP code is reading correctly from the database, I can run the PHP code and see the XML. In flash I have no errors, the datagrid appears correctly however the data is simply not there.
PHP Code
mysql_connect('localhost', 'root', '');
mysql_select_db('menu');
$sql = "SELECT item_name, item_price FROM menu1";
$res = mysql_query($sql);
header('Content-Type: application/xml');
print "<root>";
while ($row = mysql_fetch_assoc($res)) {
print "<items><itemname>".$row['item_name']."</itemname><itemprice>".$row['item_price']." </itemprice></items>";
}
print "</root>";
AS3 Code
import fl.controls.DataGrid;
import fl.data.DataProvider;
var data_grid:DataGrid = new DataGrid();
data_grid.addColumn("itemname");
data_grid.addColumn("itemprice");
data_grid.width = 600;
data_grid.rowCount = 2;
data_grid.move(10, 70);
addChild(data_grid);
var dp:DataProvider;
var request:URLRequest = new URLRequest("localhost/menu3.php");
var url_loader:URLLoader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, completeHandler);
url_loader.load(request);
function completeHandler(event:Event):void {
var ldr:URLLoader = event.currentTarget as URLLoader;
var xmlDP:XML = new XML(ldr.data);
dp = new DataProvider(xmlDP);
data_grid.dataProvider = dp;
}

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.

Flash AS3 PNGEncoder With Base64 and PHP Not Working

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.

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