Insert blob from android to oracle - php

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.

Related

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/8QA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+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

String compress in android and send to php server by URL and decompress in php server

I am trying to send compress string message by android device to PHP server.
This is my android code
ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(string.getBytes());
gos.close();
byte[] compressed = os.toByteArray();
os.close();
and this is my php code to decode
$msg=$_GET['MsgType'];
$msg2=urldecode($msg);
print gzuncompress($msg2);
but there is error
Message: gzuncompress(): data error
i searched alot on google but didn't help if any one could help me most welcome.
You should use a post variable because url's lenght is limited to few KBs...!
You should use the following code to compress the String
public static String compressAndSend(String str, String url) throws IOException {
String body1 = str;
URL url1 = new URL(url);
URLConnection conn1 = url1.openConnection();
conn1.setDoOutput(true);
conn1.setRequestProperty("Content-encoding", "gzip");
conn1.setRequestProperty("Content-type", "application/octet-stream");
GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
dos1.write(body1.getBytes());
dos1.flush();
dos1.close();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
conn1.getInputStream()));
String decodedString1 = "";
while ((decodedString1 = in1.readLine()) != null) {
Log.e("dump",decodedString1);
}
in1.close();
}
On PHP side use this,
<?php echo substr($HTTP_RAW_POST_DATA,10,-8); ?>
And please concern this Help manual for more information,
http://php.net/manual/en/function.gzuncompress.php

get high quality picture from base64 string

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.

How to upload a UIImage to MySQL via PHP from Swift?

I have an app that uploads some data to a MySQL database via some PHP web services I wrote. I have got the text data to upload successfully, but I am struggling trying to get an image to upload. Basically, the user takes a photo using their iPhone camera, I convert it to a UIImage and now want to upload it.
I have looked at the following sources for help but they haven't seemed to work for me:
How to Upload text, pdf, doc, zip file via PHP file upload to MySQL
https://www.youtube.com/watch?v=HqxeyS961Uk (The code in here wouldn't compile for me and I copied it letter for letter)
How to post a picture from iPhone app (in Swift) to MySQL database?
Saving image on db mysql through swift
Swift - uploading base64 encoded image to php and displaying the image
Getting a UIImage from MySQL using PHP and jSON
I want to upload the image and text together in the same query if possible, as they relate to one another and my MySQL table assigns an auto number for new rows.
Edit
Thanks to the answers below. I am a little unsure as to how to implement the changes you guys suggested. My Swift code at the moment to upload text data is:
let url:NSURL = NSURL(string: "http://www.website.com.au/savenewexpense.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var dataDictionary:[String:AnyObject] = ["Date" : strDate, "Staff" : strStaff, "Amount" : dblAmount, "Category" : strCategory]
var data:NSData = NSJSONSerialization.dataWithJSONObject(dataDictionary, options: nil, error: nil)!
request.HTTPBody = data
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
let response:[String:String] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String:String]
if let result = response["result"] {
if result == "success" {
NSLog("Text Data saved successfully")
if self.SendImageToServer() == true {
NSLog("Image Data saved successfully")
self.SaveSuccessful()
} else {
NSLog("Image Data failed to save")
self.DataFail()
}
} else {
NSLog("Error saving data")
self.DataFail()
}
} else {
NSLog("No response")
self.NoResponse()
}
})
task.resume()
}
and my PHP code is:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$stmt = $conn->prepare("INSERT INTO tblExpenses (Date, Staff, Amount, Category) VALUES (?, ?, ?, ?)");
$txtDate = $data['Date'];
$txtStaff = $data['Staff'];
$txtAmount = $data['Amount'];
$txtCategory = $data['Category'];
$stmt->bind_param("ssds", $txtDate, $txtStaff, $txtAmount, $txtCategory);
$stmt->execute();
echo '{"result" : "success"}';
$stmt->close();
$conn->close();
How should I implement the image into this?
Thanks
What you have to do is set the Boundary for the Image as an example use the code to Convert the NSDATA of image to the boundary values
if let dta = data as? NSData {
bodyData.appendData(String(format:"\r\n--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);
bodyData.appendData(String(format:"Content-Disposition: form-data; name=\"photo\(i)\"; filename=\"image.png\"\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);
bodyData.appendData(String(format:"Content-Type: image/png\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);
bodyData.appendData(dta);
}
Here what you do is you set the image name and then the Image Data first you convert the data using allowLossyConversion and then send the POST data with the other data to service
request.HTTPBody = bodyData
just use this to send the image

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