**$sql = 'select * from dish_category';
$results =$conn->query($sql);
$spots = array(); //array to parse jason from
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
foreach($spots as $key=>$value){
$newArrData[$key] = $spots[$key];
$newArrData[$key]['Cat_Image'] = base64_encode($spots[$key]['Cat_Image']);
}
header('Content-type: application/json');
echo json_encode($newArrData);**
Above is the PHP code, it works perfectly fine and return JSON string, now i am confused how to parse image(decode base64) in android?
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
You should do it one by one:
Get the JSON response as string in android.
Parse the JSON and get the base64 string only.
Convert the base64 string to byte array by decoding it.
Create a new ByteArrayInputStream using the byte array.
Use the input stream to create a Bitmap: BitmapFactory.decodeStream(inputStream)
Related
I am trying to add JSON generated by a PHP script to VB.net data table but my JSON is not properly formatted (missing double quotes).
PHP:
header('Content-type: text/html; charset=utf8');
$conn = mysqli_connect();
$query = mysqli_query($conn, "SELECT * FROM installations where hwid = '".$_GET["hwid"]."'");
while($row = mysqli_fetch_assoc($query)) {
$data[] = $row;
}
echo htmlspecialchars(json_encode($data), ENT_QUOTES, 'UTF-8');
json_last_error_msg();
?>
Generates this JSON which is missing additional double quotes:
[{"idinstallations":"9","hwid":"74D435E5185A","naziv_racunala":"DESKTOP-0U5","naziv_instalacije":"prip","adresa_instalacije":"Vel","ukupno_artikala":"152","ukupno_dokumenata_d":"3","ukupno_dokumenata_arh":"0","ukupno":"20.50","prva_instalacija":"2019-06-14 05:25:45","licenca":"0","Opis_opa":"beb tipo","lastContact":"2019-06-30 14:05:43","version":"1.0.0.4\/a","dnevnik_summ":"20,50","arhiva_summ":"0","mod":"1","sync":"0","syncing":"","toMail":"xxx.ttt#gmail.com","licExpire":null,"teamviewer":""}]
This is my VB.net code which I am using to set JSON to datatable:
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(http://www.something.com)
Dim json As String = result
Dim table As DataTable = JsonConvert.DeserializeObject(Of DataTable)(json)
I am sending base64 encode image from Android to SQL server DB but image is not stored in the DB folder. The android step to convert the image into base64 string is mentioned below.
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
After converting image to base64 string using volley i am posting into SQL DB. Then using PHP decode base64 string and save the image path in the DB table. The path is stored but not the image in the folder. What is wrong about it.
PHP code used:
if($_SERVER['REQUEST_METHOD']=='POST'){
$FoodName = $_POST['FoodName'];
$FoodLocation = $_POST['FoodLocation'];
$ShopName = $_POST['ShopName'];
$Type = $_POST['Type'];
$image = $_POST['image'];
require_once('dbConnect.php');
$sql ="SELECT id FROM Volley ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "images/New folder/$id.jpg";
$actualpath = "http://ccc.ccc.com/$path";
$sql = "INSERT INTO Volley (FoodName,FoodLocation,ShopName,Type,image) VALUES ('$FoodName','$FoodLocation','$ShopName','$Type','$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents('$path',base64_decode($image));
echo "Successfully posted";
}else{
echo "Could not post";
}
}else{
echo 'error';
}
BASE 64 from Android:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAGLAScDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1Fh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6lzJ/wBBgE+pH49gxHmGo22p6beXllqdlfWt
za4+3WN8feQf0H6cnGSe2X/Qtf4f5C9gv5n9yPyDP7EH/BT3TIftmkf8FebHVNUtsfYbHxX+xb8M
9R8M8Fs/8gfXzjtj6sTncpHnmt/tYftc/sS6zoWm/wDBS34WeBte+C2va3pnhax/bk/ZkbxiPhp4
J1PUGZdIH7R3whLDWvhUTwR4hX/imGJGFO3cf2yWdmyN3Hf5h6n3z2H5+xqhrnhvwz4y8P8AiHwP
4r0Gx8VeDvGWh6n4U8V+FPFelnxF4a8SeGdRLf2xo+s6Rn/ifZ7987jyKwWJwiTWMV1p1S+1LW7d
03pfdaxbTukNUI95OzV7Nbar+V2e1tX11b1PFIrrStU0iHUHurXV9JutP0zW7PW/DurfbLHxNpOp
lxpOr6FrZB/tnRiCfLkOSrkvzt5K/ND9hjStb/Zw+M/7T/8AwTKv/EF5rvgr9n+78NfG79lPXfF2
pnUfEX/DLHxZymjfDh21didnwn8aLr/h9zgEEkAZDGijG5XiliKiu3trte8pP+ZK6vZ20u7XT0OJ
O19V03du/ZbPe/nqr3O9/YS/0z/gpl/wWHvLz/SrrS779izQr
If your base64encoded string has data:image/jpeg;base64, appended infront of it, then you need to remove it before base64_decode
You can use something like this for it
str_replace("data:image/jpeg;base64,","",$image);
UPDATE
I tried to convert your string here But it seems to be corrupted. The base64 string is not proper.
This might happen, if there are new line characters in the code. So try replacing \n or any other white spaces from the string before decoding it. You can use str_replace("\n", "", $image) for that as well. Try and let me know
I'm returning image as base64 string in server side. In client side app takes this base64 string and convert it to byte[] and then to Bitmap and at the last step sets this bitmap to ImageView. My problem is returned image quality. It looks poor; I can see the pixels of this image...
Upload part
Client side (upload):
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
Server side (accepts uploaded image):
$_image = $_REQUEST['image'];
$binary = base64_decode($_image);
// for inserting it to db...
$sql = "INSERT INTO users (`_profile_pic`) VALUES ('$_image')";
$connect->query($sql);
Accept part
Server side (gets base64 string from db)
$user_data = "SELECT _name, _profile_pic FROM users WHERE _id = {$_id}";
$data = $connect->query($user_data);
while ($row = $data->fetch(\PDO::FETCH_ASSOC))
$collectedResult[] = $row;
echo json_encode($collectedResult, JSON_UNESCAPED_UNICODE);
Client side (sets image to ImageView (problematic part) )
_picture = (ImageView) findViewById(R.id.profile_imageView);
byte[] decodedString = Base64.decode(profile_pic_value, Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
_picture.setImageBitmap(bmp);
At this moment I don't know how to restore or increase the quality.
Any helpful comment, answer appreciated.
Regards,
Mirjalal.
P.S This question maybe duplicate of another question(s), but I couldn't find duplicate one. :D
I found this but I don't know how to use.
It is possible that you loose color depth during decoding into RAM. Android has defaults as to which color format it decodes bitmaps. See following example which saves RAM but still maintains acceptable image quality.
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, Base64.DEFAULT);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length, options);
}
Take a closer look at the Bitmap.Config.RGB_565 parameter.
I am fetching data from a php server in its normal format..the columns are details and image..
I want the image in base64 format nd the details in utf8 format..all this data into one array that will be json encoded and will then be parsed at android side..How do i do this..so that i can Json parse in this manner..
String result= convertStreamToString(is);
JSONObject json=new JSONObject(result);
jArray=json.getJSONArray("details");
for(int i=0;i<jArray.length();i++)
{
JSONObject c=jArray.getJSONObject(i);
String detail=c.getString("details");
String image=c.getString("image");
Log.v("topics", topic);
is.close();
}
The php code:
while($out=mysql_fetch_assoc($result))
{
echo $out;
print_r(base64_encode($out[image]));
echo base64_encode($out['image']);
echo utf8_encode($out['details']);
$tempImage = base64_encode($out['image']);
echo $tempImage;
$tempDetails = utf8_encode($out['details']);
$post[] = array("image"=>$tempImage);
$post []= array("details"=>$tempDetails);
}
echo json_encode(array("login"=>$post));
i think that you can use this link to learn about this
Issues-parsing data to the php and jsons
or visit this : http://androidexample.com/JSON_Parsing_-_Android_Example/index.php?view=article_discription&aid=71&aaid=95
I'm trying to send an image from an sql database to an android client. I'm doing this by way of a php middleman. The code stops working due to a null returning of the method below.
My php code(works fine to encode image into base64(decoded the encoding and it worked)):
<?php
//get image
function ob_base64_encode($c) {
$a=base64_encode($c);
$arr = array('base64' => $a);
return json_encode($arr);
}
$image=resize(48,80,$image);
// And pass its name as a string
ob_start('ob_base64_encode');
imagepng($image);
ob_end_flush();
?>
My android code:
public static Bitmap getIm(String IP, int height, int width)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//Network queries and gets response(works)
String result = Network.getResponse(IP, nameValuePairs);
//manually decode string since for some reason JSON decode won't work(also works)
String r=result.split(":\"")[1];
r=r.split("\"")[0];
//decode string
byte[] decodedString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
//returns null
}