Send raw png byte[] with GetRawTextureData post with AddBinaryData: no data - php

I post to server raw byte [] of texture but shows 5B in sql database and when this data is downloaded the file is empty. Can you please provide guidance?
I post to server the raw byte[] of a texture like so:
byte [] imgByte0 = uploadedTex.GetRawTextureData();//uploadTex is Texture2D
Debug.Log("Byte Len " + imgByte0.Length);//results in 722160
WWWForm form = new WWWForm();;
form.AddBinaryData("rgbImgBytes", imgByte0, "image/png");
UnityWebRequest www = UnityWebRequest.Post("https:address.php", form);
yield return www.SendWebRequest();
I post it to my php and insert into sql database BLOB (I'm aware there are other preferred alternatives to store images, imgs are/will be stufficiently small not the question here):
$thisRGBImg=$_FILES['rgbImgBytes'];
$stmt = $conn->prepare("INSERT INTO $imageTable `thisRGBImg` VALUES (?)");
$stmt->execute([$thisRGBImg];
Png image is 300Kb, however it shows as 5B held in sql database BLOB. I further confirm when I download these raw bytes to file (as per https://thoughtbot.com/blog/avoiding-out-of-memory-crashes-on-mobile#streams-to-the-rescue) and resulting file is empty:
using (UnityWebRequest myWebRequest = UnityWebRequest.Post(path, formData2))
{
myWebRequest.downloadHandler = new ToFileDownloadHandler(new byte[64 * 1024], savePathWithFileName);
yield return myWebRequest.SendWebRequest();
}
public ToFileDownloadHandler(byte[] buffer, string filepath) : base(buffer)
{
this.filepath = filepath;
fileStream = new FileStream(filepath, FileMode.Create, FileAccess.Write);
}
protected override bool ReceiveData(byte[] data, int dataLength)
{
if (data == null || data.Length < 1)
{
Debug.Log("ReceiveData - received a null/empty buffer");
return false;
}
received += dataLength;
Debug.Log("Data received " + dataLength + " total received " + received);
//if (!canceled) fileStream.Write(data, 0, dataLength);//replaced for bw below
if (!canceled)
{
var bw = new BinaryWriter(File.Open("path", FileMode.OpenOrCreate));
bw.Write(data);
bw.Flush();
bw.Close();
}
return true;
}

Related

PhpMyAdmin table gives empty column

I am working on a project to send sensor data to phpmyadmin table using GET request.
I am not able to see sensor data in the table when I consider my Arduino to be the client, but when I use this URL on my Google chrome browser it shows the result (ex. 40).
It seems the problem is with the Arduino code.
int samples[NUMSAMPLES];
void loop() {
// Thermistor
uint8_t i;
float average;
// take N samples in a row, with a slight delay
for (i=0; i< NUMSAMPLES; i++) {
samples[i] = analogRead(THERMISTORPIN);
delay(10);
}
// average all the samples out
average = 0;
for (i=0; i< NUMSAMPLES; i++) {
average += samples[i];
}
average /= NUMSAMPLES;
// convert the value to resistance
average = 1023 / average - 1;
average = SERIESRESISTOR / average;
float Steinhart;
Steinhart = average / THERMISTORNOMINAL; // (R/Ro)
Steinhart = log(Steinhart); // ln(R/Ro)
Steinhart /= BCOEFFICIENT; // 1/B * ln(R/Ro)
Steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
Steinhart = 1.0 / Steinhart; // Invert
Steinhart -= 273.15; // convert to C
Serial.print("Temperature ");
Serial.print(Steinhart);
Serial.println(" *C");
delay(5000);
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected to server");
// Make a HTTP request:
client.println("GET /add.php?");
client.print("Steinhart=");
client.print(Steinhart);
}
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
}
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
} // end of void setup()
And here is my PHP code: add.php file
<?php
include("connect.php");
$link=Connection();
$Steinhart = ""; // or null !!
$timeStamp="";
$Steinhart = isset($_GET['Steinhart']) ? $_GET['Steinhart'] : '';
date_default_timezone_set("Asia/Dubai");
$timeStamp = date('Y-m-d H:i:s', time());
$query= "INSERT INTO `time` (`id`, `timeStamp`, `Steinhart`) VALUES (NULL, '$timeStamp','$Steinhart')";
mysqli_query($link, $query);
mysqli_close($link);
?>
I Usually send data from the Arduino board to PhpmyAdmin(Wamp Server or XXamp) with the help of NodeJS. It is pretty easy to send data with the help of NodeJS.
Here i attach the code.
var request = require('request');
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var serialPort = new SerialPort("COM5", {
baudrate: 9600,
parser: serialport.parsers.readline("\n")
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log(data);
});
});
serialPort.on('data', sendSerialData);
function sendSerialData(data) {
request({
uri: "http://127.0.0.1/write_data.php?value="+data,
method: "GET",
timeout: 10000,
followRedirect: true,
maxRedirects: 10
}, function(error, response, body) {
console.log(body);
});
}
By this you can easily send the data. Also you can just follow this link
http://www.instructables.com/id/PART-1-Send-Arduino-data-to-the-Web-PHP-MySQL-D3js/
Hope it will help

imagecreatefromstring is causing 500 internal server error

I have bitmao instance i convert this instance into base64string and send it to server over php function. Now i am decoding this string and calling imagecreatefromstring but this function is giving 500 internal server error. I want this image to be store into file.
My .net function is as follows:
Bitmap icon = new Bitmap("C:\\Users\\HP\\Desktop\\mun.ico");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
icon.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
HttpWebRequest m_ObjRequest; //Request which needed to be sent to server
HttpWebResponse m_ObjResponse; // Response which is sent back from the server to the client
StreamReader reader = null; // making a stream reader to read the web pageand initialize it to null
string m_Url = "http://192.168.1.30/muneem/erp/uploadIcon.php"+ "?bitmap=" + base64String; // the url of that web page
string m_Response = "";
m_ObjRequest = (HttpWebRequest)WebRequest.Create(m_Url); // creating the url and setting the values
m_ObjRequest.Method = "GET";
m_ObjRequest.ContentType = "application/json; charset=utf-8";
//m_ObjRequest.ContentLength = 500;
m_ObjRequest.KeepAlive = false;
m_ObjResponse = (HttpWebResponse)m_ObjRequest.GetResponse(); // getting response from the server
using (reader = new StreamReader(m_ObjResponse.GetResponseStream())) // using stream reader to read the web page
{
m_Response = reader.ReadToEnd();
reader.Close(); // Close the StreamReader
}
m_ObjResponse.Close();
m_ObjRequest = null;
m_ObjResponse = null;
My php code to handle this encoded bitmap string is as follows:
$bitmap=$_GET['bitmap'];
$data = base64_decode($bitmap);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
encoded bitmap string is as follows:
$bitmap="Qk02BAAAAAAAADYAAAAoAAAAEAAAABAAAAABACAAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9qwA//asAP9L/9v/S//b//asAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9qwA/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b//asAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b//asAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2rAD/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2rAD/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/9qwA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/S//b/0v/2//2rAD/9qwA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
why i am getting this error on imagecreate from string?
BMP format is not supported by imagecreatefromstring. Allowed formats are: JPEG, PNG, GIF, WBMP, and GD2.

Windowsphone to PHP communication through Webclient

I want to upload an Image i selected with the PhotoChooserTask.
The Selection itself works fine and i can open the Image.
I also already decoded it to Base64 (Works).
Since I can't find any working example on how to work with httpwebrequest on windowsphone I tried it the following way.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
MyImage.Source = bmp;
String str = BitmapToByte(MyImage);
String url = "http://klopper.puppis.uberspace.de/php/app/image.php?image="+ str;
LoadSiteContent(url);
}
}
The rest of the code is working fine.
I get: System.IO.FileNotFoundException
If I change the str to "test" it's working.
Is the problem, that the string is too long?
private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
const int BLOCK_SIZE = 4096;
Uri uri = new Uri("http://localhost:4223/File/Upload", UriKind.Absolute);
WebClient wc = new WebClient();
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;
// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};
// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};
// Write to the WebClient
wc.OpenWriteAsync(uri, "POST");
}
Reference
to post image file in windows phone 7 application

uploading image and php POST method in windows phone

this is my first post. please be kind :)
i'm trying to get picture from media library (in WP 7), upload it using httpwebrequest, and save it to folder in the server. i succeed to convert the image to string of byte (but i suspect there are something wrong here), send the string using POST, and retrieve it in my php web page.
Everything seems to be working well, but when i convert the string of byte to jpeg (using imagecreatefromstring function) it always come up empty picture. here is my code in C# and php. I'm sorry for my English if it's not perfect (or far from perfect) :)
this is my c# code along with some comments
public partial class MainPage : PhoneApplicationPage
{
string uploadUri = #"http://192.168.138.1/meeshot/upload.php"; //php web page for retrieve and saving file in the server
string requestImageName = "picture"; //variable name for post ---- >$_POST['picture']
string postdata; //byte data generate using BitmapToByte function
// Constructor
public MainPage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
Image image1 = new Image ();
private void button1_Click(object sender, RoutedEventArgs e) //user choosing photo from media library
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
HttpWebRequest req = HttpWebRequest.Create(
new Uri(this.uploadUri)) as HttpWebRequest;
postdata = BitmapToByte(image1); //convert image to byte. My suspisicion there is something wrong here
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(HttpWebRequestButton2_RequestCallback, req);
}
}
private void HttpWebRequestButton2_RequestCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
using (var requestStream = req.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(requestImageName+"="+this.postdata); //writing "picture=bytedata"
writer.Flush();
}
}
req.BeginGetResponse(HttpWebRequestButton_Callback, req);
}
private void HttpWebRequestButton_Callback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
var resp = req.EndGetResponse(result);
var strm = resp.GetResponseStream();
var reader = new StreamReader(strm);
this.Dispatcher.BeginInvoke(() => {
this.DownloadedText.Text = reader.ReadToEnd(); //the web page will print byte data that has been sent using httpwebrequest. i can see that byte data has benn sent sucessfuly.
this.DownloadedText.Visibility = System.Windows.Visibility.Visible;
});
}
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image) //i suspect there is something wrong here
{
Stream photoStream = ImageToStream(image);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(bimg);
wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
bytearray = ms.GetBuffer();
}
string str = Convert.ToBase64String(bytearray);
return str;
}
and this is my code in php web page
if(isset($_REQUEST['picture'])) //check
{
$myFile = "picture.jpg";
$fh = fopen($myFile, 'wb') or die("can't open file");
$stringData = $_REQUEST['picture']."<br>";
$im = imagecreatefromstring($stringData);
if ($im) {
imagejpeg($im);
fwrite($fh, $im);
imagedestroy($im);
}
fclose($fh);
echo $stringData;
}
Please look at my question here: Photo upload with parameters to a PHP page
And my solution here: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/

Sent and received data isn't the same size

I have server in C++ writen with boost.asio and php client. when i send over small amount of data i get all the data but when i send long string i loose most of it.
Here is the part where i send data from my server, it says i have sent out 65536 bytes
void handle_write(const boost::system::error_code& /*error*/,
size_t size/*bytes_transferred*/) {
cout <<size<<endl;
}
void handler_read(const boost::system::error_code&, std::size_t size) {
istream is(&buffer);
string myString;
getline(is, myString);
Manager myManager(myString);
string response = myManager.getResponse();
boost::asio::async_write(socket_,
boost::asio::buffer(response),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
Here i make the string i will be sending
string getMap(string name, string pass) {
if (name == "admin" && pass == "123") {
string response = "";
ConvertTypes types;
response = types.intToString(MAP_HEIGHT) + " ";
response += types.intToString(MAP_WIDTH) + "\r\n";
for (int i=0; i<MAP_HEIGHT;i++) {
for (int j=0;j<MAP_WIDTH;j++) {
response += types.intToString(
worldMap[i][j].getHeight()) + " ";
response += types.intToString(
worldMap[i][j].getIsTown()) + " ";
response += string (1, worldMap[i][j].getTetrain())
+"\r\n";
}
}
return response;
} else {
return "";
}
}
On php side i read the sent data, stream_get_meta_data says i only received 8183 bytes of data.
print_r($this->socket->getStatus());
for ($i=0; $i<$MAP_HEIGHT;$i++) {
for ($j=0; $j<$MAP_WIDTH;$j++) {
$this->response = $this->socket->readLine();
$this->response = explode(' ', $this->response);
echo "<p>";
echo "$i $j <br>";
print_r($this->response);
echo '<br>';
print_r($keyArray);
$map[$i][$j] = array_combine($keyArray, $this->response);
$this->response = $this->socket->readLine();
} }
}
You can send one large block via socket, but receiving side might get several blocks of smaller sizes, for example:
send -> 10000 bytes
receive <- 3000 bytes
receive <- 2000 bytes
receive <- 4500 bytes
receive <- 500 bytes
this is only an example, TCP does not guarantee send and receive blocks will be the same size.
I've found a answer. I was sending data from server in unsafe way. When async_write gave up controll to something else rest of the data was lost.
You have to pass string to this class:
class shared_const_buffer {
public:
// Construct from a std::string.
explicit shared_const_buffer(const std::string& data)
: data_(new std::vector<char>(data.begin(), data.end())),
buffer_(boost::asio::buffer(*data_))
{
}
// Implement the ConstBufferSequence requirements.
typedef boost::asio::const_buffer value_type;
typedef const boost::asio::const_buffer* const_iterator;
const boost::asio::const_buffer* begin() const { return &buffer_; }
const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
private:
boost::shared_ptr<std::vector<char> > data_;
boost::asio::const_buffer buffer_;
};
and send this buffer not raw string. That way you don't loose data.

Categories