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.
Related
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"); ?>
Below is the code. The code works perfectly fine. It displays the content when both the EditText is left blank or has some string value that is available in the mysql database . My problem is that i want to display an error message when the input from the editText does not match with the JSON object or the returnString that store the result of the Mysql query after decoding JSON.
for eg if input='abi' //input from edittext
khasi:abirt //khasi is column from the database with value abirt
output : khasi abirt will be displayed
but i want an error to be displayed when input does not match at all with any of the words from the khasi column of the database instead of a blank page activity.
for eg : input='kljfldskfsldhf'
khasi column does not consist the input word
outout : blank page activity
String result;
String returnString;// to store the result of MySQL query after decoding JSON
String input;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_meaning);
Intent intent = getIntent();
intent.setClass(DisplayMeaningActivity.this, MainActivity.class);
input =intent.getStringExtra(MainActivity.MEANING_INPUT);
tv = (TextView) findViewById(R.id.textView1);
// declare parameters that are passed to PHP script i.e. the name "meaning" and its value submitted by user
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://kffg.netii.net/konnect.php?name="+input, // your ip address if using localhost server
postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
//parse json data
try{
returnString = "";
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", Khasi: "+json_data.getString("Khasi")+
", English: "+json_data.getString("English")
);
//Get an output to the screen
returnString += "\n\n" + "Kyntien : " + json_data.getString("Khasi") + "\n"+ "Meaning: " + "\n"+ "" + json_data.getString("English");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
need to use an if loop with stringValue.contains("editTextvalue") condition.
It'l be like:
if (inputString.contains(columnNames)) {
//yes
} else {
//no, then print error
}
Since you already have your "result" in String, that shouldn't be a problem (?) .
Did not exactly understand the columns of the database issue but for the khasi column of your database, you can make an arrayList of of names and compare the string with a for each loop.
for(String string: columnNames){
if(input.equals(name)){}
}
Maintain an arrayList where you add string for each time you get data for khasi like:
arrayList.add(json_data.getString("Khasi"));
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.
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
I am writing a php program to write a binary file (may be video or image files). I would like to make it as a web service and call it from another application like c#, mac etc.
My code is give below,
<?php
$fileChunk = $_POST["filechunk"];
$vodFolder = 'D:\\HYSA SVN\\Trunk\\workproducts\\source\\hysa_he\\web\\entertainment\\';
$vodFile = $vodFolder . "abcd.mov";
$fh = fopen($vodFile, 'ab');
flock ($fh, LOCK_EX);
$varsize = fwrite($fh, $fileChunk);
fclose($fh);
?>
But when I called the php web service from a c# code, the abcd.mov is creating in the location, but its size is only one kb. I suspects that, the writing in halted when a character ‘&’ found in the binary file. I read the php documentation and found that, fopen with binary mode ‘b’ will solve this issue? But it is not working. Can somebody help me ?
This is my c# code.
BinaryReader b = new BinaryReader(File.Open("d:\\image38kb.jpg", FileMode.Open));
int pos = 0;
int length = (int)b.BaseStream.Length;
byte[] bt = b.ReadBytes(length);
char[] ch = b.ReadChars(length);
HttpWebRequest request = null;
Uri uri = new Uri("http://d0327/streamtest.php");
request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential obj = new NetworkCredential("shihab.kb",
"India456*", "tvm");
request.Proxy.Credentials = obj;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bt.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes("filechunk=");
byte[] rv = new byte[bytes.Length + bt.Length];
System.Buffer.BlockCopy(bytes, 0, rv, 0, bytes.Length);
System.Buffer.BlockCopy(bt, 0, rv, bytes.Length, bt.Length);
writeStream.Write(rv, 0, bt.Length);
}
string result = string.Empty;
using (
HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
Well the problem is not in the fwrite part, that works fine.
However, POST requests in HTTP look like this:
POST /somepage.php HTTP/1.1
Content-Length: 34
variable1=blah&var2=something else
As you can see, variables are divided by ampersands (&) (as well as equal signs (=) for the key - value mapping)... So, even when using POST requests, ampersands are not safe characters.
To solve this, you could try another transfer method, for example, TCP/IP socket connection, or simply escape the ampersands with, say '\x26' (the ASCII value of ampersand) and escape all the backslashes (\) with '\x5C'... You'd have to edit the PHP code to parse these values.