Sending a image to mysql using android, json and php
I was able to get my bitmap converted to a properly formatted string using
converting-images-to-json-objects
Here is the code in android
JSONObject values = new JSONObject();
values.put(KEY_CONTRACTUUID, con.UUID);
...
if (con._sig != null) {
String encodedImage = getStringFromBitmap(con._sig);
values.put(KEY_CONTRACTSIGIMAGE, encodedImage);
private static String getStringFromBitmap(Bitmap bitmapPicture) {
/*
* This functions converts Bitmap picture to a string which can be
* JSONified.
*/
final int COMPRESSION_QUALITY = 100;
String encodedImage;
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
return encodedImage;
}
now that it is in base64 and a string I need to retrieve it properly to place in my BLOB in mysql
I am not using namevalue pairs or any of that nonsense - simply send it as json and get the json string like so:
$json = json_decode($HTTP_RAW_POST_DATA,true);
echo var_dump(HTTP_RAW_POST_DATA);
...
$varsigimage = $json['sigimage'];
$formatedJSONimage = "{'sigimage': '$varsigimage'}";
var_dump($formatedJSONimage);
$sigImagedecoded = json_decode($formatedJSONimage);
var_dump($sigImagedecoded);
i need to call json_decode on the image to get it out of 64bit to place in the blob correct?
However to do this I need to use the function json_decode, but json_decode assumes I will give it a JSONObject, and since I have many more objects in my $json object, i need to recreate a single JSON object with just the image inside of it, and pass that to the json_decode
but it retuns json_error of type SYNTAX
What am I doing wrong, What is the correct approach of converting the base64 string to a blob?
and yes, I am going to have the same question on getting it out of the blob back to a base64 string
json_decode parses a JSON string and returns an associative array, mimicking the key/value pairs in the JSON string.
It seems like you are missing another step: you need to decode the base64-encoded image string back to a bitmap. e.g. in your code:
$json = json_decode($HTTP_RAW_POST_DATA,true);
echo var_dump(HTTP_RAW_POST_DATA);
...
$varsigimage = $json['sigimage'];
$image_bitmap = base64_decode($varsigimage); // decode the string back to binary
You should now be able to save $image_bitmap as a BLOB in your database.
Related
Trying to send arraylist data to server using php as bridge from Android (using Volley), and successfully getting data into database table (and also getting response as submit, I mentioned in php) in Android
So everything looks perfect, if we talk about db connection, storage and response, but one unusal issue always getting 2 in table field, instead the original value
::::imageDataInString::::: {"b":"2020-01-01_00:01:11.jpg"}
::::imageDataInString::::: {"b":"2020-01-01_00:01:21.jpg"}
::::imageDataInString::::: {"b":"2020-01-01_00:01:31.jpg"}
::::Response::::: <br />
<b>Warning</b>: Illegal string offset 'image_name' in <b>C:\xampp\htdocs\test\send_data.php</b> on line <b>15</b><br />
<br />
submit
Here is the foreach, I'm using in php to upload all the data available in a list
$content = $_POST['my_images'];
$json = json_decode($content, true);
foreach ($json as $key => $value) {
$image_name = $value["image_name"];
}
android code
ImageData imageData = new ImageData();
imageData.setImageName(array[0]);
String imageDataInString = new Gson().toJson(imageData);
Log.d("::::imageDataInString::::", imageDataInString);
....
params.put("my_images", imageDataInString);
in my csv, available in raw folder of res in Android, I have these data:
2020-01-01_00:01:11.jpg
2020-01-01_00:01:21.jpg
2020-01-01_00:01:31.jpg
There are a few points to note:
GSON converts the variable names of the class (ImageData) as keys and appends the values, to form the JSON. Hence, you need to use the same variable names, as you have used in the ImageData class to fetch the data, in your PHP Code.
ImageData imageData = new ImageData();
imageData.setImageName(array[0]);
String imageDataInString = new Gson().toJson(imageData);
Hence, the array key should be array["ImageName"]
In your PHP code, the second line, where you are JSON decoding the $content variable, the variable $json is already converted in an Array. You don't need to iterate and fetch corresponding keys.
Hence, you should do something like this:
$content = $_POST['my_images'];
$json = json_decode($content, true);
$image_name = $json["ImageName"];
With this, the variable $image_name will hold the value which you are looking for.
I'm trying to send data from a VB.NET Application to a php application, i found this code:
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(),contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Dim data = Encoding.UTF8.GetBytes(jsonSring)
Dim result_post = SendRequest(uri, data, "application/json", "POST")
at: source
But I can't get the posted data on php. It sends the headers, but the data no.
So, I need help to figure it out what is missing.
I also had same issue and got solution from comments only. As you are passing binary data then in php you need to read binary data as raw input
To get the Raw Post Data:
<?php $postdata = file_get_contents("php://input"); ?>
byte[] data = Base64.decode(jsonChildNode.optString("profilePicture"),Base64.DEFAULT);
String profilePicture = new String(data,"UTF-8");
My php encode:
$row1['profilePicture'] = base64_encode($row1['profilePicture']);
The output from Android is: ???JFIF????...
It's not displaying the picture.
You are loading the image as string and not processing it back to binary.
ImageView imgViewer = (ImageView) findViewById(id.of.your.img_viewer);
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
imgViewer.setMinimumHeight(dm.heightPixels);
imgViewer.setMinimumWidth(dm.widthPixels);
imgViewer.setImageBitmap(bm);
As you can see, in this example the data in byte array is loaded to a Bitmap object so that you can get the image representation.
I try to send long array from android to PHP via JSON. I did the same thing with Javascript and worked but with JAVA it gets confusing. When I send the parameters, long array list changes.
This is the part that creates the list.
JSONArray list = new JSONArray();
for (int i = 0; i < users.size(); i++) {
list.put(users.get(i).getId());
}
This is the code in JAVA that send the data.
public JSONObject sendFacebookFriendList(JSONArray list) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("list", list.toString()));
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.getJSONFromUrl(accountServer, params);
return json;
}
And this is the code that receives the data in PHP.
$list = $_POST['list'];
$result = array("success" => 1, "list" => $list);
While sending with Javascript the $list variable was becoming long array directly but I couldn't send it same way with JAVA.
When I send the list back to JAVA from PHP without any change I see that each array element has \" at the head and the end
So this list:
list= ["517565130","523709375","524503024","524620558","524965930", ...
becomes this:
"list":"[\"517565130\",\"523709375\",\"524503024\",\"524620558\", ...
So I cannot parse this array in PHP.
I couldn't find any way to send the long/int array in a proper way.
I appreciate if someone can fix this or suggest another way.
Thanks
I solved the problem. The thing I skipped was decoding the json array that encoded at android part. So after getting the posted data it is needed to be decoded like this;
$list = $_POST['list'];
$obj = json_decode($list);
And then I can use $obj as array.
This is how normally we retrieve raw data from server with httppost or get.
This is one of the tutorial from google search
Tutorial link
use a HttpPost to get the data,
convert response to string parse
JSON data, and use it as you want
But what if i want retrieve data and together with related image into my android apps?What is the appropriate method to go for?
This is example of my data.
id image_name caption
1 01.jpg Abcd
and my image store in somewhere of my server.
upload/background_image/01.jpg
Convert the image in base64 string in the server side, and retrieve it from the application.
then use the following to decode the base64 string into bitmap
public static String encodeTobase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
// Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public static Bitmap decodeBase64(String input)
{
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
you can response them as url, and when you need the image content, issue another request.
or
you can read the image content, base64_encode it and response as string