get high quality picture from base64 string - php

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.

Related

PARSE JSON (Encode base 64) STRING in Android

**$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)

base 64 string from Android to SQL not decoding and store in folder using php

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
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD92vGf
jfwN8MPBvir4h/EvxVZeD/A/g7Q9S1zxV4q1vUjp3hrw34a05mAA1YHknbx1Oc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19V03du/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

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');
im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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/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.

Insert blob from android to oracle

I'm working with Oracle database. I use PHP for my web service and Android as the client which will send blob data to Oracle DB. I use this code
Bitmap imageUpload = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageUpload.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] image_data = baos.toByteArray();
String converted_image = Base64.encodeBytes(image_data);
to decode and send it as base64 encoding, then send it to the web service with this code
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("TITLE", title));
nameValuePairs.add(new BasicNameValuePair("IMAGES", converted_image));
json = jsonParser.makeHttpRequest(url, "POST", nameValuePairs);
This is my PHP code to insert to oracle db
if(isset($_POST["TITLE"]) && isset($_POST["IMAGES"]))
{
$title = $_POST["TITLE"];
$image = $_POST["IMAGES"];
$gambar = file_get_contents($image);
$query = "INSERT INTO images (TITLE, IMAGES) VALUES (:TITLE, EMPTY_BLOB()) RETURNING IMAGES INTO :IMAGES";
$parse = oci_parse($connect, $query);
$lob_a = oci_new_descriptor($connect, OCI_D_LOB);
oci_bind_by_name($parse, ":TITLE", $title);
oci_bind_by_name($parse, ":IMAGES", $lob_a, -1, OCI_B_BLOB);
oci_execute($parse, OCI_DEFAULT);
if($lob_a->save($gambar))
{
oci_commit($connect);
$lob_a->free();
}
else
{
oci_rollback($connect);
}
}
The PHP code successfully insert the query to the oracle db, but when I see the record the blob does not show anything like this
I think the best solution to this question is to use web service, encode the picture with base64 encoding then decode it while the file transferred.

How can I send an image from an sql database to an android client?

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
}

Categories